- 首页 > it技术 > >
Function.prototype.myCall = function(content){
// call 方法如果第一个参数传入nullthis会指向 window
content = content || window
// content.fn = this// 在这给content 参数对象添加了一个fn的方法结束后要删除这个方法
// 要判断这个方法是否已经存在 所以这个fn必须是唯一的
varuniqueID = "00" + Math.random();
// 定义一个随机数
while (content.hasOwnProperty(uniqueID)) {
// 如果参数上有这个随机数,就再生成一个
uniqueID = "00" + Math.random();
}
content[uniqueID] = this
let args = [...arguments].slice(1)
// 如果call方法有返回值定义这个方法的然后返回这个结果
var result = content[uniqueID](...args)//执行完后,要删除这个方法,不改变传入的参数
delete content[uniqueID]
// 删除之后,原参数就不改变了
return result
}var person = {
fullName: function(txt) {
console.log(txt + this.firstName + " " + this.lastName);
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
console.log(person1) //{firstName: 'John', lastName: 'Doe'}right
person.fullName.myCall(person1, "Hello, ");
// 输出"Hello, John Doe"
console.log(person1)// {firstName: 'John', lastName: 'Doe', fn: ?}error
推荐阅读