“如何使用严格”修改“this”的规则在Javascript? [英] How does "use strict" modify the rules for "this" in Javascript?
问题描述
我试图理解使用严格的这个的规则;修改如下。
I'm trying to understand what rule for "this" that "use strict"; modifies in the below case.
阅读后( http://unschooled.org/2012/03/understanding-javascript-this/ )我最好的猜测是,因为functon isStrictModeOn()没有附加到任何东西,所以这是指null 。这被认为是一个更合理的替代Javascript只是将它附加到全局对象。在这种情况下,使用严格的变更是否正确解释?
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.
推荐答案
这几乎是正确的。在严格模式下,当一个函数在没有接收器的情况下被调用时,这个
是 undefined
(不是空
)。该函数的更好版本是:
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';
}
这类函数的一个固有问题是严格性是词汇决定的,像范围一样,所以它是静态的。包含其自己的use strict;
的测试器功能不是很有用;它实际上只告诉您JavaScript运行时是否理解严格模式。一个没有自己的use strict;
告诉你它所定义的词汇上下文是否处于严格模式。那就是:
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();
}
会在通话时告诉您是否 use strict;
对于定义函数的范围有效。我想这可能有用。但是,如果对该函数的引用泄漏到其严格性不同的其他上下文中,它将继续在其定义时报告其静态严格性。
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.
就个人而言,我会选择通过在最外层调用use strict;
来确保我的代码绝对处于严格模式。这样就没有必要检查它了。
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.
这篇关于“如何使用严格”修改“this”的规则在Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!