【发布时间】:2019-04-18 08:09:57
【问题描述】:
关注 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 中运行
【问题讨论】:
-
你的意思是“somebar”和“somevariable”在你的帖子中是一样的吗?
标签: javascript node.js