What is the difference in method borrowing using call method and using "=" operator in JavaScript?

Viewed 67

Consider the following objects

var person1 = {
   name: 'Sam',
   age: 26,
   job: 'teacher',
   testMethod : function() {
     //do something
   }
};

var person2 = {
   name: 'John',
   age: 30,
   job: 'student'
};

I want to borrow testMethod from person1 to person2.

//Using = operator
person2.testMethod = person1.testMethod;
person2.testMethod();

//Using call method
person1.testMethod.call(person2)

What is the difference between these two ways of borrowing?

1 Answers

The call method will not add the testMethod to your second object person2, it will only change the binding of this inside testMethod body, so instead of this pointting to person1 it will be pointting to person2.

Example:

var person1 = {
  firstName:"John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

person1.fullName(); //this will yield John Doe
person1.fullName.call(person2); //this will yield Mary Doe

person2.fullName = person1.fullName;
person2.fullName(); //this will yield also Mary Doe

From MDN:

The call() allows for a function/method belonging to one object to be assigned and called for a different object.

call() provides a new value of this to the function/method. With call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

Related