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
  • 72,740
  • 7
  • 86
  • 98
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
  • 33,923
  • 10
  • 53
  • 80
-2

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

Ele
  • 33,468
  • 7
  • 37
  • 75
Strikegently
  • 2,251
  • 20
  • 23