let person = {
name: 1,
getName: function () {
return this.name
}
}
let person1 = {
name: '你猜'
}
//我们在这封装出来一个 自己的call方法
//这个Mycall方法肯定得是 在原型上 才能被每个function给访问到
Function.prototype.Mycall = function (context) {
//我们先进行一个判断 判断一下 this(也就是这个方法的调用者)是不是function
if (typeof this !== 'function') {
return console.log('error');
}
//如果是function的话 我们就进行接下来的操作
//对我们这个context 进行判断 如果为空 就是window
context = context || window
context.fn = this //我们知道 这里面的this其实是 一个函数 我们将这个函数 放在context上 以便 this这个函数里面的this指向这个context
//当然 真正的call方法会接受参数
//这个参数 肯定是 除去我们要让this指向的那个参数
let args = [...arguments].slice(1)
let result = context.fn(...args)
return result
}
console.log(person.getName.Mycall(person1, 1, 2, 3, 4));
手写call方法(代码演示)
最新推荐文章于 2024-03-11 22:58:25 发布