手写 call、apply、bind

从this的隐式绑定入手
我们都知道函数中this的指向只取决于该函数的调用位置,且其有四种绑定形式。即

  • 默认绑定
  • 隐式绑定
  • 显示绑定
  • new绑定

而显示绑定是借用了一些方法。如call、apply,bind。但是它们的怎么实现的呢?
答:它们均是基于隐式绑定基础之上的

先来看什么是隐式绑定,看下面代码:

function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
obj.foo(); 

全局情况下的默认绑定之所以绑到了全局,是因为函数调用位置在全局的上下文中,而这里的调用位置拿到的上下文是obj的。

call,apply的实现均是基于隐式绑定,知晓了思路实现便非常简单了
实现:

Function.prototype.myCall = function(context = window) {
    context.fn = this;
    let res = context.fn(...([...arguments].slice(1)));
    delete context.fn;
    return res;

}
Function.prototype.myApply = function(context = window, arr) {
    context.fn = this;
    let res;
    if (!arr) {
        res = context.fn();
    } else {
        res = context.fn(...arr);
    }


    delete context.fn;
    return res;

}
console.log(...[1, 2, 3]);

Function.prototype.myBind = function(contextcontext = window) {
    let that = this;
    let args = [...arguments].slice(1);
    return function() {
        return that.apply(context, args);
    }
}

function a(b, c) {
    console.log(this.d,b,c);

}
let e = {
    d: 1
}
a.myApply(e,[2,3])
a.myCall(e,2,3)
a.myBind(e,2,3)()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值