简体   繁体   中英

Use of var in the global namespace

I'm reading "you don't know javascript" and I find some trouble with one example in the book "This & Object Prototypes".

When discussing the different rules for this , specifically in the "Implicit binding" paragraph, the author gives this example:

function foo() {
    console.log( this.a );
}

var obj = {
    a: 2,
    foo: foo
};

var bar = obj.foo; // function reference/alias!

var a = "oops, global"; // `a` also property on global object

bar(); // "oops, global"

However when trying this on JSFiddle I get an undefined output in console instead of the "oops, global".

Conversely, if I define a without var or using window.a I get the output intended by the author regardless of strict mode.

Why is this happening? Did something in ES6 change the way global variables should be declared?

The default settings for JS Fiddle wrap the JS in a function and assign it as an load event handler.

Your tests are not in the global scope.

JS小提琴默认JS配置

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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