Tuesday, March 27, 2012

Javascript Constructor return rules

Tonight we have a student asked about what if we return a primitive types in a constructor function, like the below:

function Person() {
   this.name = "Roy";
   return "abc";
}

What would be the return if we instantiate this constructor?

var me = new Person();
console.log(me); // what would you expect to see??

The result is you will get an instance of "Person".  Some people may question "the return was a string, how come it still return an instance of Person?"   Well, it is all related to the "new" keyword.

Whenever you instantiate a constructor ( or a Class ) using "new" keyword.  The javascript interpreter will enforce you to return an object.  If you do not return an object ( just like the above ), the javascript interpreter will enforce this rule by returning an instance of a current constructor.

So it will be similar to the following:

function Person() {
   this.name = "Roy";
   return this;
   //return "abc";
}

However, if you define an object at the return, the javascript interpreter won't care about it.

function Person() {
   this.name = "Roy";
   return { name: "Joyce" };
}

The above code works because it is returning an object, but it won't be an instance of Person.

So, remember, if you return a "primitive types" in a constructor, when you instantiate the constructor with a "new" keyword, you will always get the instance of the Constructor back.  However, if you return an object, you won't have any issue.

No comments:

Post a Comment