Search code examples
javascriptobjectconstructorprototypecall

call() not working for object created from function contructor


I have created one constructor function named House in JS.

function House(color, floor, location){
    this.color = color;
    this.floor = floor;
    this.location = location;    
}

Using this prototype I have created two more objects named myHouse and myOldHouse.

var myHouse = new House('brick red', '1st floor', 'saltlake');
var myOldHouse = new House('Yellow', '2st floor', 'Koikhali');

Then I have added one new method called address to the myHouse object.

myHouse.address = function(address){
   this.address = address;
   console.log('My address is '+this.address); 
}

Now I am want to add this method to myOldHouse object as well using the call function.

myHouse.address.call(myOldHouse, '2G');

But when I am calling myOldHouse.address(), it is showing error.


Solution

  • Call when invoked in a method (address in your case) just tells the scope the method should run in. When passing myOldHouse, In the address method the this keyword refers to myOldHouse object. So now myOldHouse.address must print out '2G'. Here in your case, you are accessing a method that is unaccessible for an object here. The root cause is that the method address is not shared between the two objects, namely myHouse and myOldHouse. You've created these objects from House function which means these two will have access to all the properties associated with House .In your example, you've associated address method to myHouse which restricts it's access to the objects created from myHouse function.

    For example:

    var myHouseChild = new myHouse(...);

    Now, myHouseChild object will have access to both the properties of House and myHouse functions.

    In order to make address method work for myOldHouse you have to set it in the prototype of House function so that it is shared among it's objects.

    Like, House.prototype.address = () => {};

    Refer this answer for inner workings of new keyword.