2
(function (){
  'use strict';
  function Foo() { 
    this.foo = function() { 
      setTimeout(function(){ console.log(this); }, 0);
    } 
  }
  new Foo().foo();
}())

厳密モードを宣言しなかった場合、グローバル オブジェクトがコンソール (ウィンドウ) に出力されます。

BUT、厳密モードが宣言されていることを考えると、 undefined がコンソールに出力されることを期待していました。

参照:

「つまり、ブラウザーでは厳密モード関数内で this を介してウィンドウ オブジェクトを参照することができなくなりました。」

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode#.22Securing.22_JavaScript

更新: 期待される動作を実現するには、新しい実行コンテキストを作成し、そのコンテキスト内でこれを次のように参照する必要があります。

(function (){
  'use strict';
  function Foo() { 
    this.foo = function() { 
      setTimeout(function(){ (function() { console.log(this); }()) }, 0);
    } 
  }
  new Foo().foo();
}())
4

0 に答える 0