Why does this not log undefined to the console when run in Chrome's console window?

61 Views Asked by At
(function (){
  'use strict';
  function Foo() { 
    this.foo = function() { 
      setTimeout(function(){ console.log(this); }, 0);
    } 
  }
  new Foo().foo();
}())

If I had not declared strict mode then the global object would be printed to the console (i.e. window).

BUT, given that strict mode is declared, I was expecting undefined to be printed to the console.

Reference:

"That means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function."

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

Update: to achieve the expected behavior you need to create a new execution context and refer to this within that context like so:

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

There are 0 best solutions below