变量提升(hoisting)
在JavaScript中,函数、变量的声明都会被提升(hoisting)到该函数或变量所在的scope的顶部。即——JavaScript的变量提升.
var x = 5; alert(x); // 5 alert(y); // undefinedvar y = 7; alert(y); // 7
此处变量y未声明时便可以使用,其实是因为JavaScript会自动将声明语句提升到顶部。
而第一次alert(y)时显示undefined,说明只提升了声明,未提升赋值语句。等同于以下:var y;alert(y); // undefinedy = 7;alert(y); // 7
javascript中一个名字(name)以四种方式进入作用域(scope),其优先级顺序如下:
语言内置:所有的作用域中都有 this 和 arguments 关键字;
形式参数:函数的参数在函数作用域中都是有效的;
函数声明:形如function foo() {};
变量声明:形如var bar;
名字声明的优先级如上所示。也就是说如果一个变量的名字与函数的名字相同,那么函数的名字会覆盖变量的名字,无论其在代码中的顺序如何。但名字的初始化却是按其在代码中书写的顺序进行的,不受以上优先级的影响。看代码:
(function(){ var foo; console.log(typeof foo); //function function foo(){} foo = "foo"; console.log(typeof foo); //string var foo;})();
function test() { foo(); // TypeError "foo is not a function" bar(); // "this will run!" var foo = function () { // function expression assigned to local variable 'foo' alert("this won't run!"); } function bar() { // function declaration, given the name 'bar' alert("this will run!"); }}test();
函数表达式的声明:
foo(); // TypeError "foo is not a function"bar(); // validbaz(); // TypeError "baz is not a function"spam(); // ReferenceError "spam is not defined"var foo = function () {}; // anonymous function expression ('foo' gets hoisted)function bar() {}; // function declaration ('bar' and the function body get hoisted)var baz = function spam() {}; // named function expression (only 'baz' gets hoisted)foo(); // validbar(); // validbaz(); // validspam(); // ReferenceError "spam is not defined"
JavaScript中的作用域
JavaScript中运行以下代码我们会发现,i为10?
for (var i = 0; i < 10; i++) { // some code}return i; //10
在如Java、C、C++等其他语言中,作用域一般为for语句、if语句或{}内的一块区域,称为块级区域(block-level scope);
而在JavaScript中,作用域则是函数域(function-level scope).var x = 1;console.log(x); // 1if (true) { var x = 2; console.log(x); // 2}console.log(x); // 2function foo() {var x = 1;if (x) { (function () { var x = 2; // some other code }());}console.log(x); // x is still 1.} var foo = 1;function bar() { if (!foo) { // 由于var foo被提升,此处foo为undefined,进入if var foo = 10; } alert(foo); // 10}bar();
var a = 1;function b() { a = 10; return; function a() {}}b();alert(a); // 1
引用自: