How does “use strict” modify the rules for “this” in Javascript?

假装没事ソ 提交于 2019-11-28 09:37:08

问题


I'm trying to understand what rule for "this" that "use strict"; modifies in the below case.

After reading (http://unschooled.org/2012/03/understanding-javascript-this/) my best guess is that since the functon isStrictModeOn() is not "attached" to anything, this refers to null. Which is suppose to be a more sensible alternative to Javascript just attaching the this to the global object. Is that the correct interpretation of the change that "use strict" is making in this case?

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.

回答1:


That's almost correct. In strict mode, when a function is invoked without a receiver then this is undefined (not null). A better version of that function would be:

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

An inherent problem with functions like that is that "strictness" is determined lexically, like scope, so it's static. A tester function that includes its own "use strict"; isn't very useful; it really only tells you whether the JavaScript runtime understands strict mode. One without its own "use strict"; tells you whether the lexical context in which it's defined is in strict mode. That is:

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

will tell you, when called, whether a "use strict"; was in effect for the scope at which the function is defined. I guess that could be useful. However, if a reference to that function "leaks" into some other context whose "strictness" differs, it's going to continue to report on its static strictness at the point of its definition.

Personally, I would opt for simply ensuring that my code is definitely in strict mode by invoking "use strict"; at the outermost layer possible. That way there's really no need to check for it.



来源:https://stackoverflow.com/questions/17150951/how-does-use-strict-modify-the-rules-for-this-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!