在之前我还写过手写call的代码源码 可以参考
手写call方法(代码演示)_Phil_16的博客-CSDN博客
其实两个区别不大 也就是参数这块的一个区别 我们判断一下 就行
let person = {
name: 1,
getName: function () {
return this.name
}
}
let person1 = {
name: '你猜ba'
}
//我们在这封装出来一个 自己的apply方法
//这个Myapply方法肯定得是 在原型上 才能被每个function给访问到
Function.prototype.Myapply = 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
let result;
// console.log(arguments); //如果我们的arguments[1]存在 也就说明 我们有除了this要指向的对象 还有数组参数
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn //使用完以后 清理掉
return result
}
console.log(person.getName.Myapply(person1, [1, 2, 3, 4]));