js 超详细的手写call、apply、bind

手写call

Function.prototype.myCall = function (context, ...arg) {
    // 此时的 this 指向的是小数点前面的变量 也就是 obj.getName
    // 并将 obj.getName 赋值给 context 的 fn 属性
    // 使用 context.fn 执行的时候,this 指向小数点前面的对象 context 
    context.fn = this;
    let result = context.fn(...arg);
    return result;
}
let obj1 = {
    name: "xiaohei",
    age: 18,
    getName: function () {
        console.log(this.name);
    }
}

let obj2 = {
    name: "xiaobai"
}

obj1.getName.call(obj2); //  'xiaobai'

手写apply
+ 与 call 基本一致,就是穿的是数组,不再需要解构

Function.prototype.myApply = function (context, arg) {
    // 此时的 this 指向的是小数点前面的变量 也就是 obj.getName
    // 并将 obj.getName 赋值给 context 的 fn 属性
    // 使用 context.fn 执行的时候,this 指向小数点前面的对象 context 
    context.fn = this;
    let result = context.fn(arg);
    return result;
}
let obj1 = {
    name: "xiaohei",
    age: 18,
    getName: function () {
        console.log(this.name);
    }
}

let obj2 = {
    name: "xiaobai"
}

obj1.getName.myApply(obj2); //  'xiaobai'

手写bind

Function.prototype.myBind = function (context, ...arg) {
    // 记录 调用 this 的主体 也就是 obj1.getName
    let _this = this;
    let fn = function () {
        // context 要改成的 this 对象,也就是 obj2 , 参数可能会从两个地方传过来,进行参数合并
        _this.apply(context, arg.concat(Array.prototype.slice.call(arguments)));
    }
    // 保证返回的函数 原型链上的属性 不丢失
    if (_this.prototype) {
        fn.prototype = Object.create(this.prototype);
    }
    // 不会立即执行,返回 一个函数
    return fn;
}

obj1.getName.myBind(obj2, 11)(22); // xiaobai Arguments(2) [11, 11...
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值