使用原生的call
var person = {
getName() {
// this指向person
console.log(this);
return this.name
}
}
var man = {
name: '小余'
}
// 把this指向修改为man
person.getName.call(man)
使用手写call
var person = {
getName() {
console.log(this);
return this.name
},
}
var man = {
name: '小余'
}
// 手写call方法
Function.prototype.myCall = function (content) {
//在JavaScript中,如果this没有被正确设置,它会默认指向全局对象(在浏览器中为window对象)
// 所以getName中打印的this为window
// this()
// 如果this现在则为getName()不是一个函数则抛出一个错误提示
if (typeof this !== "function") {
throw new Error('这不是一个函数')
}
// 不传入形参则为window
content = content || window
// 传入多个形参,把除了第一个content其余都赋值给args
const args = [...arguments].slice(1)
// 将getName即this赋值给content.fn设为新函数 此时this指向为content即man
content.fn = this
// 将参数传给getName()
const res = content.fn(args)
// 添加新属性需要删除,防止产生冲突
delete content.fn
return res
}
person.getName.myCall(man)