【问题标题】:How does "use strict" modify the rules for "this" in Javascript?“use strict”如何修改Javascript中“this”的规则?
【发布时间】:2013-06-13 14:37:38
【问题描述】:

我试图了解“使用严格”的“this”规则;在以下情况下进行修改。

在阅读 (http://unschooled.org/2012/03/understanding-javascript-this/) 之后,我最好的猜测是,由于函数 isStrictModeOn() 没有“附加”到任何东西,所以它指的是 null。这被认为是仅将 this 附加到全局对象的 Javascript 更明智的替代方案。这是对“use strict”在这种情况下所做更改的正确解释吗?

http://www.novogeek.com/post/ECMAScript-5-Strict-mode-support-in-browsers-What-does-this-mean.aspx

function isStrictMode(){
    return !this;
} 
//returns false, since 'this' refers to global object and '!this' becomes false

function isStrictModeOn(){   
    "use strict";
    return !this;
} 
//returns true, since in strict mode, the keyword 'this' does not refer to global object, unlike traditional JS. So here,'this' is null and '!this' becomes true.

【问题讨论】:

    标签: javascript this use-strict


    【解决方案1】:

    这几乎是正确的。在严格模式下,当一个函数在没有接收者的情况下被调用时,this 是undefined(不是null)。该函数的更好版本是:

    function isStrict() {
      "use strict";
      return (typeof this) === 'undefined';
    }
    

    这样的函数的一个固有问题是“严格性”是由词法确定的,就像范围一样,所以它是静态的。包含自己的"use strict"; 的测试器函数不是很有用;它实际上只告诉您 JavaScript 运行时是否理解严格模式。没有自己的"use strict"; 会告诉您定义它的词汇上下文是否处于严格模式。那就是:

    function isStrict() {
      function test() {
        return (typeof this) === 'undefined';
      }
      return test();
    }
    

    会在调用时告诉您"use strict"; 是否在定义函数的范围内有效。我想这可能很有用。但是,如果对该函数的引用“泄漏”到“严格性”不同的其他上下文中,它将继续在其定义时报告其静态严格性。

    就个人而言,我会选择通过在最外层调用"use strict"; 来确保我的代码绝对处于严格模式。这样就真的不用检查了。

    【讨论】:

    • @dandavis 我不知道;只是习惯。它们是不必要的,但它们不会伤害任何东西。 (我假设您的意思是 typeof 子表达式周围的括号。)
    • 酷,很高兴知道,但你怎么知道它在全球范围内活跃?
    • @dandavis 我发布的第二个帖子会有点这样做;问题在于了解 JavaScript 中“全局”的含义。
    猜你喜欢
    • 2011-11-10
    • 2014-02-17
    • 2019-03-14
    • 2011-07-10
    • 2011-10-23
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多