简体   繁体   English

何时起吊?

[英]When does hoisting apply?

I use this pattern for some of my code: 我将这种模式用于一些代码:

(function () {
    var a,
        b,
        c,
        d;

    a = // some module definition
    b = // some module definition
    c = // some module definition
    d = // some module definition

}());

What I've noticed is that if b needs access to a it must be defined before it. 我注意到的是,如果b需要访问a则必须在它之前定义它。 So b can reference a , but a can not reference b . 因此b可以引用a ,但是a不能引用b

I found this strange because I thought a process called hoisting allowed me to not have to define my modules in any particular order. 我发现这很奇怪,因为我认为一个称为提升的过程使我不必按任何特定顺序定义模块。

But what I'm finding is that ordering does matter. 但是我发现排序确实很重要。

Only the var declaration is hoisted. 仅挂起var声明。 Not the = assignment. 不是=赋值。

This means you can refer to a variable whose var declaration comes later in the function without getting a ReferenceError , but its value will be undefined until the assignment actually takes place. 这意味着您可以引用一个变量声明为var的变量,而该变量在函数中稍后出现,而没有得到ReferenceError ,但是在实际分配之前,其值将是undefined的。

(function() {

    alert(b);  // undefined
    var b = "foo";
    alert(b);  // "foo"
})();

Because of the "hoisting", the above example effectively turns into this: 由于“吊装”,上面的示例实际上变成了:

(function() {
    var b;
    alert(b);  // undefined
    b = "foo";
    alert(b);  // "foo"
})();

Hoisting means the declaration happens earlier but the assignment doesn't move. 吊装意味着声明会更早发生,但分配不会移动。 The variable will be declared but will be undefined. 该变量将被声明,但未定义。

Hoisting can cause confusion due to scoping issues. 吊装可能会由于范围问题而引起混乱。 So for instance: 因此,例如:

var a = 1;
var somFunc = function(){
  var b = a;
  alert(b); // alert undefined
  var a = 3
}
someFunc();

The alert in this case is 'undefined' as the second var a is hoisted above the var b , but the assignment is left till after, and the first a assignment is overwritten because it is outside the scope. 在这种情况下,警报是“未定义的”,因为第二个var a hoistedvar b之上,但是分配一直保留到之后,而第a变量被覆盖,因为它不在范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM