Functions can return objects. We have seen a bunch of tutorials on functions before. Here, we will see some expected and some unexpected behavior when function returns objects especially when that function is used as a constructor function

 

function person(name){
  return {
    name:name
  };
}

var tom = person('TomTom');
console.log(tom.name)

 

Here, person() is not used as an constructor. It is a simple function returning a object using the object literal notation.

 

Let us see what happens when constructor function returns an object. Concentrate!

 

function Person(name){
  this.name = name
  return {
    name:'xyz'
  };
}

var tom = new Person('TomTom');
console.log(tom.name)

 

Now, Person() function is being used as a constructor and that constructor return an object.

 

What does console.log(tom.name) print? It prints xyz as the output. This was not expected based on our previous knowledge on objects.

 

It appears that, when a constructor function returns an object, the reference of this keyword inside the constructor function shifts to the object returned by the constructor function.

 

The reference does not change when constructor function does not return an object. It is better if we abstain ourself from making constructor function returning an object.

 

0 Do You Love This Article ?

CT

Hello All! You are reading the author(s) profile of CorvineLabs Team. We may be 1,2 or ..any in number. Let that remain withing us. You enjoy our write up. If you want to join the team than do Contact Us.

Leave a Reply

Your email address will not be published. Required fields are marked *