继MDN之后:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
如果不是严格模式,则函数中的“this”将指向全局对象。
但是,当尝试修改函数中的全局变量时,它并不像我想象的那样工作。是否有一些解释或一个人可以参考的规范?
// this.somevariable = 'this is in global var'; // will not be in Global
somevariable = 'this is in global var'; // will make it to global
function something() {
somebar = 'foo'; // this will not change the global variable
this.somebar = 'foo'; // this will not change the global variable
console.log(this.somevariable);
}
something();
console.log( this.somebar ); // somebar undefined
P.S我只想弄清楚'this'关键字是如何工作的。我知道修改全局变量是一个坏主意,也不是使用严格模式。
*在节点v10.14中运行
如果一个函数不是boxed,那么this
是一个全局的草率模式,而undefined
是在一个函数内的严格模式。
this
引用Node.js模块范围中的模块对象(module.exports
)。
区别在于this
在这里指的是一个模块:
console.log(this.somebar); // this === module.exports
并指这里的全球:
console.log(this.somevariable); // this === global
我想这个例子可以解释你们所有人:
// in node
function somethingNode() {
console.log(global === this);
}
// in Browser
function somethingBrowser() {
console.log(window === this);
}
somethingNode(); // true
somethingBrowser(); // true
在你的最后一个字符串中,你引用module.exports
对象,这就是为什么它不相等