js手写call方法的实现
下面是代码
let name = "windowName"
var man = {
name: 'manName'
}
var person = {
getName: function () {
return this.name
}
}
Function.prototype.myCall = function (context) {
// 判断this是否是function
if (typeof this !== 'function') {
throw new Error('error: this not a function')
}
// 如果没有传入context则指向window
context = context || window
// 将传入的其余参数取出
var args = [...arguments].slice(1)
// 创建context.fn 并将this指向指向其
context.fn = this
const res = context.fn(...args)
delete context.fn //删除临时创建的context.fn
return res
}
console.log(person.getName.call(man, 1, 2, 3))//manName
console.log(person.getName.myCall(man, 1, 2, 3))//manName