Function.prototype.myCall = function(content){
// call 方法如果第一个参数传入 null this会指向 window
content = content || window
// content.fn = this // 在这给content 参数对象添加了一个fn的方法 结束后要删除这个方法
// 要判断这个方法是否已经存在 所以这个fn必须是唯一的
var uniqueID = "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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。