JavaScript'使用严格';内部功能

时间:2013-02-28 12:18:43

标签: javascript ecmascript-5 strict

Chrome开发者控制台中测试了一些js代码,我有点困惑。

我知道在严格模式函数中,当引用关键字时,该函数不是对象的方法,应该接收 undefined 而不是全局对象

function test(){
    "use strict";
    return this===undefined;}
test(); 

输出 false

"use strict";
function test(){
    return this===undefined;}
test(); 

false

(function test(){
    "use strict";
    return this===undefined;}());

输出 true

只是想澄清一下。 ʕ•ᴥ•ʔ我是js的新手。

3 个答案:

答案 0 :(得分:4)

您注意到的只是开发者控制台工作方式的副作用。当您在那里输入代码时,实际上会发生这种情况(有关详细信息,请参阅this answer):

eval.call(null, "with (window) { \
                     function test() { \
                         'use strict'; \
                         console.log(this); \
                     } test(); \
                 }");

这是对eval间接调用,这意味着它将始终在全局执行上下文中执行(在浏览器中,即window)。

实际上,函数绑定到全局对象,因此this保存对全局对象的引用,就好像您在网页中(而不是在控制台中)这样做:

function test(){
    "use strict";
    return this === undefined;
}

test(); // true
test.call(window); // false

答案 1 :(得分:2)

一切都很好。如果您通过某个HTML页面(而不是开发控制台)运行代码,则结果符合预期(始终为this===undefined)。

另外在最新的Firefox(Firebug)中:

function test(){
    "use strict";
    return this===undefined;}
test(); 
>> true

所以这似乎只是另一个Chrome的错误(功能?)。感觉它与通过开发控制台传递的代码略有不同。

另请注意,订单很重要:

<script>
    console.log( 'Me First!' );

    "use strict";

    function test(){
        console.log( this );
    }
    test();

</script>

>>> "Me First!"
>>> Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

可是:

<script>
    "use strict";

    console.log( 'Me later!' );

    function test(){
        console.log( this );
    }
    test();

</script>

>>> undefined
>>> "Me later!"

答案 2 :(得分:2)

Chromium Developer Console中的一个错误导致this仍然引用全局对象。相同的代码在位置栏和文档中使用javascript:指定的方式工作。

您可以像这样测试(2个控制台输入):

var global = (function () { return this; }());

"use strict";
function test () { return this === global; }
test();

和(一个或多个控制台输入)

var script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode(
  'function test () { "use strict"; return this === undefined; }; console.log(test());'
));
document.body.appendChild(script);

在Chromium Version 25.0.1364.97 Debian 7.0(183676)中进行了测试。