JavaScript中的变量提拔、作用域

变量提拔(hoisting)

在JavaScript中,函数、变量的声明都会被提拔(hoisting)到该函数或变量地点的scope的顶部。即——JavaScript的变量提拔.

var x = 5;    
alert(x);     // 5 
alert(y);     // undefined
var y = 7;    
alert(y);     // 7

此处变量y未声明时便可以运用,实在是因为JavaScript会自动将声明语句提拔到顶部。
而第一次alert(y)时显现undefined,申明只提拔了声明,未提拔赋值语句。等同于以下:

var y;
alert(y);    // undefined
y = 7;
alert(y);    // 7

javascript中一个名字(name)以四种体式格局进入作用域(scope),其优先级递次以下:

  1. 言语内置:一切的作用域中都有 this 和 arguments 关键字;

  2. 形式参数:函数的参数在函数作用域中都是有用的;

  3. 函数声明:形如function foo() {};

  4. 变量声明:形如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(); // valid
baz(); // 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(); // valid
bar(); // valid
baz(); // valid
spam(); // 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);     // 1
if (true) {
    var x = 2;
    console.log(x); // 2
}
console.log(x);     // 2

function 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



援用自:JavaScript Scoping and Hoisting–written by ben cherry

    原文作者:点蚊子熏烟
    原文地址: https://segmentfault.com/a/1190000005794611
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞