javascript - 在 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)
这两种借贷方式有什么区别?
解决方案
该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(),您可以编写一次方法,然后在另一个对象中继承它,而无需为新对象重写方法。
推荐阅读
- c++ - Vynograd 算法的错误输出
- sql - 是否可以从 MSSQL 中的加密日期字符串转换日期格式
- pattern-matching - 为什么连接运算符 @ 或算术运算符不是合法的模式构造函数?
- html - 如何将文本标签更改为正确的?
- c# - 如何为也在网络聊天中工作的 MSTeams 重写自适应卡片提交操作?
- unix - 在 Unix 中写入文件时如何附加字符串
- blazor-server-side - 服务器端 Blazor 应用程序的 ASP.NET Core 身份验证
- java - Android Firebase 数据库检查用户名是否已被使用
- image - 如何在颤动中缓存一小部分图像?
- reactjs - 为什么当我将组件放入
它的构造函数调用了两次?