【问题标题】:Can a function modify 'this' object in Javascript?函数可以修改 Javascript 中的“this”对象吗?
【发布时间】: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 中运行

【问题讨论】:

标签: javascript node.js


【解决方案1】:

如果函数不是boxed,则this 在草率模式下是全局的,在函数内部是严格模式下的undefined

this 指的是 Node.js 模块范围内的模块对象 (module.exports)。

不同的是this在这里指的是一个模块:

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

这里指的是全局:

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

【讨论】:

    【解决方案2】:

    我认为这个例子可以说明一切:

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

    在您的最后一个字符串中,您引用了 module.exports 对象,这就是它不相等的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 2010-11-06
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多