简体   繁体   English

在全局名称空间中使用var

[英]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". 我正在阅读“您不了解javascript”,并且在“ This&Object Prototypes”一书中发现了一个示例的问题。

When discussing the different rules for this , specifically in the "Implicit binding" paragraph, the author gives this example: 在讨论了不同的规则this ,特别是在“隐式绑定”的段落中,作者给出了这样的例子:

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". 但是,当在JSFiddle上尝试此操作时,我在控制台中得到了未定义的输出,而不是“ 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. 相反,如果我定义a不带var或使用window.a ,则无论严格模式如何,我都会得到作者想要的输出。

Why is this happening? 为什么会这样呢? Did something in ES6 change the way global variables should be declared? ES6中的某些内容是否改变了声明全局变量的方式?

The default settings for JS Fiddle wrap the JS in a function and assign it as an load event handler. JS Fiddle的默认设置将JS包装在一个函数中,并将其分配为加载事件处理程序。

Your tests are not in the global scope. 您的测试不在全球范围内。

JS小提琴默认JS配置

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

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