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
  • 56,346
  • 6
  • 64
  • 75
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
  • 32,042
  • 9
  • 48
  • 75
-2

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

Ele
  • 32,412
  • 7
  • 33
  • 72
Strikegently
  • 2,043
  • 16
  • 20