开发者

Trying to fully understand JavaScript hoisting

Edit Looks like it was an issue on my part and my usage of jsfiddle :?

Ive been reading a couple of articles on hoisting lately, one is by Nicholas Zakas, and the other is by Ben Cherry.

Im trying to follow the examples and just test on my own to make sure I fully grasp it but Im having an issue mainly with this example,

if (!('a' in window)) {
    var a = 1;
}
console.log(a);

Instead of logging undefined its logging 1. If I am understanding everything correctly, a should be undefined, because it should exist in the window scope due to the var statement being hoisted to the top, so it should not be assigned the value.

But the following is acting as expected,

(function bar(){
    console.log(foo);
    var foo = 10;  
    console.log(baz);
})();

foo is undefined开发者_如何学Go, and baz is not defined. I have a fiddle here with both examples. Really just trying to wrap my head around this. Has something changed since these articles were written maybe? If anyone can shed some light on this it would be appreciated. Im using Chrome 14 when testing.


Change the wrap in the fiddle to no wrap(head)

http://jsfiddle.net/rlemon/VjCqF/3/


You have JSFiddle set to onLoad, so var a is scoped to the onLoad function. Change it to no wrap and you get:

undefined
undefined
Uncaught ReferenceError: baz is not defined


In the second example, hoisting transforms the code into this:

(function bar(){
    var foo;
    console.log(foo);
    foo = 10;  
    console.log(baz);
})();

So foo is undefined during the first call to log. The declaration is always hoisted to the top of the enclosing function, but assignment is never hoisted with it.


object.a === undefined; // true, but a in object; // true

var object = {a: undefined};

('a' in object); // is true because a is a property of object


Hoisting is understood differently but to my understanding what it does is

Whenever you create an variable/functions it sets up a memory space for you.It does not put the variable/functions on the top of execution context.

Type 'this/window' in console you'll find your var/functions sitting there lexically.

for example:

a; //returns undefined 
b(); //returns Hello World   
var a = "Hello";
    function b() {
        console.log('Hello World');
    }

If it is placed on top during execution then it should output 'Hello' not 'undefined' functions will get excuted.Variables won't get excuted. Please avoid hoisting excute the vars after it is being declared:

var a = "Hello";
    function b() {
        console.log('Hello World');
    }
a; //returns Hello

b(); //returns Hello World   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜