javascript - JavaScript 中使用 call 方法借用方法和使用 "="运算符的方法借用有什么区别?

标签 javascript methods apply

考虑以下对象

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

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

我想从 person1 借用 testMethod 给 person2。

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

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

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

最佳答案

call 方法不会将 testMethod 添加到您的第二个对象 person2,它只会更改 this< 的绑定(bind)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:

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.

关于javascript - JavaScript 中使用 call 方法借用方法和使用 "="运算符的方法借用有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015805/

相关文章:

R:将计算列添加到数据框列表中

javascript - 具有父元素内部属性的vuejs测试组件

javascript - 使用 POST API 上传多部分表单

java - 如何调用 ArrayList 上的方法

Java测试文件LocalDate

r - 如何创建使用Apply(或创建函数)将字符日期跨多列日期转换为R中的日期

javascript - Appcelerator : JSON. 解析不在套接字内执行任何操作

javascript - 访问父类中的变量

javascript - 单独适用于页面上多个元素的方法

R 获取列的所有组合并对它们执行函数返回对称矩阵?