首页 > 解决方案 > 在 JavaScript 中使用调用方法和使用“=”运算符的方法借用有什么区别?

问题描述

考虑以下对象

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

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

我想将 testMethod 从 person1 借给 person2。

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

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

这两种借贷方式有什么区别?

标签: javascriptmethodsapply

解决方案


call方法不会将 添加testMethod到您的第二个对象person2,它只会更改this内部testMethod主体的绑定,因此不是this指向person1它,而是指向person2

示例

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

来自 MDN:

call() 允许为不同的对象分配和调用属于一个对象的函数/方法。

call() 为函数/方法提供了 this 的新值。使用 call(),您可以编写一次方法,然后在另一个对象中继承它,而无需为新对象重写方法。


推荐阅读