[英]Can a function modify 'this' object in Javascript?
遵循 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
PS我只是想弄清楚'this'關鍵字是如何工作的。 我知道修改全局變量和不使用嚴格模式都是一個壞主意。
*在節點 v10.14 中運行
如果一個函數沒有被裝箱,那么this
是一個全局的在 sloppy 模式下和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
對象,這就是它不相等的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.