js手写call函数

Function.prototype.myCall = function (context, ...arr) {
    if (context === null || context === undefined) {
       // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window)
        context = window 
    } else {
        context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象
    }
    const specialPrototype = Symbol('特殊属性Symbol') // 用于临时储存函数
    context[specialPrototype] = this; // 函数的this指向隐式绑定到context上
    let result = context[specialPrototype](...arr); // 通过隐式绑定执行函数并传递参数
    delete context[specialPrototype]; // 删除上下文对象的属性
    return result; // 返回函数执行结果
};
let test = {
    name: "test"
}, fun = {
    fn: function () {
          console.log(this.name)
    }
}
fun.fn.myCall(test)
context[specialPrototype] = this; 这句话的个人理解
这个函数里面context是当你使用myCall的this指向对象
当你使用上面方法之后相当于在这个指向对象里面新增了一个key为specialPrototype,value为函数的this的键值对(this的指向问题,当你使用myCall的时候,this是调用myCall的函数,即上面的fun.fn,即最终是在context里面新增了一个specialPrototype:fun.fn)
context[specialPrototype](...arr);当你执行这行代码的时候 其实是调用了fun.fn,但是这个时候 里面的this的指向变为调用specialPrototype的context
就这样context中的this就完成代替了fun.fn中的this
 

猜你喜欢

转载自www.cnblogs.com/web-chuan/p/11592261.html
今日推荐