0

The Foo is being executed from the window global object like this:

  new Foo();   // false why?
  Foo();       // true

 function Foo()
 { 
     alert(this == window); 
 };

But when I run this function Foo code, the alert message says false, why is this when Foo is executed from the global window object?

Nora
  • 65
  • 4

3 Answers3

3

It's because you used new. The new operator creates a new object, sets that object's prototype to be Foo.prototype, then invokes Foo with this set equal to the newly-created object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Nicholas Tower
  • 37,076
  • 4
  • 43
  • 60
1

It's not in the window context. It's in the function context. If you'd like it to be in the window context, you can do

foo.call(window);
ControlAltDel
  • 28,815
  • 6
  • 42
  • 68
-2

JavaScript has function-level scoping. In your example, this is referring to the Foo function.

Ele
  • 31,191
  • 6
  • 31
  • 67
Strikegently
  • 1,738
  • 14
  • 19