ray
ray

Reputation: 145

this in javascript constructor function

function Foo() {  
    alert(this === a);//return false!   **why this is not equal a?**  
}  
var a = new Foo();//create a new object

foo is a constructor,why this in the 'Foo' is not equal with 'a'.

Upvotes: 0

Views: 135

Answers (2)

david
david

Reputation: 4278

i think "this" referring to as a object, but "this.a" is true as that is the object

Upvotes: -1

jfriend00
jfriend00

Reputation: 708156

The assignment to the variable a has not yet happened when you're inside the constructor. The sequence of events is:

  1. Create a new object
  2. Run the constructor
  3. Assign the new object to the variable a.

Upvotes: 6

Related Questions