函数可以在Javascript中修改'this'对象吗?

问题描述 投票:1回答:2

继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中运行

javascript node.js
2个回答
2
投票

如果一个函数不是boxed,那么this是一个全局的草率模式,而undefined是在一个函数内的严格模式。

this引用Node.js模块范围中的模块对象(module.exports)。

区别在于this在这里指的是一个模块:

console.log(this.somebar); // this === module.exports

并指这里的全球:

console.log(this.somevariable); // this === global

-1
投票

我想这个例子可以解释你们所有人:

// in node
function somethingNode() {
    console.log(global === this);
}

// in Browser
function somethingBrowser() {
    console.log(window === this);
}

somethingNode(); // true
somethingBrowser(); // true

在你的最后一个字符串中,你引用module.exports对象,这就是为什么它不相等

© www.soinside.com 2019 - 2024. All rights reserved.