考虑以下对象
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/