变量函数提升

变量被提升

var x = 10;
function x(){};
console.log(x);// 打印出10

因为变量声明和函数声明会被解释为:

var x;
function x(){};
x = 10;
console.log(x);// 10

函数被提升

声明式函数会自动将声明放在前面并且执行赋值过程,而变量式则是先将声明提升,然后到赋值处再执行赋值。

function test(){
  foo();// TypeError "foo is not a function"
  bar();// "this will run!"
  var foo = function(){
    alert("this won't run!");
  }
  function bar(){// function declaration,given the name 'bar'
    alert('this will run !');
  }
}
test();

实际上等价于:

function test(){
  var foo;
  var bar;
  bar = function(){
    alert("this won't run !");
  };
  foo();// TypeError "foo is not a function"
  bar();// "this will run!"
  foo = function(){
    alert("this won't run !");
  }
}
test();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容