关于ts中的指针问题call,bind, apply

相同

  • 都可以应用于改变this的指向问题

不同

  • call 传入…args
  • apply 传入数组
  • bind 传入…args

实现方法

call

  • 原理主要是将方法复制给调用的this,再进行删除
  • 代码

function dmCall(context: any) {
    
    
    const fn = Symbol();
    context[fn] = this;
    const args = [...arguments].slice(1);
    let result = context[fn](...args);
    return result;
}

apply

与call一样, 只是将参数改成了数组

function dmApply(context: any, args?: any[]) {
    
    
    const fn = Symbol();
    context[fn] = this;
    let result;
    if( args === null || args === undefined) {
    
    
        result = context[fn](args);
    } else if (typeof args === 'object') {
    
    
        console.log(...args)
        result = context[fn](...args);
    }
    delete context[fn];
    return result;
}

bind

  • 比较复杂,需要新建一个函数返回,其中需要用到apply
  • 原理就是,创建一个方法,将参数放入,返回该函数
function myBind(context) {
    const fn = Symbol();
    context[fn] = this;
    const self = context;
    const args = [...arguments].slice(1);
    function bind() {
        const res = [...arguments, ...args];
        return context[fn].apply(self, res);
    }
    return bind;
}
Function.prototype.myBind = myBind
math1.add.myBind(a, 10)(1);

猜你喜欢

转载自blog.csdn.net/monk96/article/details/126267530