原生js实现手写call、apply、bind

实现call()方法

call都做了哪些操作?

  1. 将函数设为对象的属性;
  2. 指定this到函数,并传入给定参数执行函数;
  3. 执行之后删除这个函数;
  4. 如果不传入参数,默认指向window;
Function.prototype.mycall = (context,...args) {
    // 判断this是否函数,否返回typeerror
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    context = context || window;
    context.fn = this;

    const res = context.fn(...args);

    delete context.fn;
    return res; 
}

实现apply()

apply跟call类似

Function.prototype.myapply = (context,...args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    context = context || window;
    context.fn = this;
    args = args && args[0] || [];

    const res = context.fn(...args);

    delete context.fn;
    return res;
}

实现bind()

bind要做什么?

  1. 返回一个函数,绑定this,传递预制参数;
  2. bind返回的参数可以作为构造函数使用
Function.prototype.mybind = (context,...args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    let fn = this;
    
    const bind = (...args2) => {
        // fn.apply 来保持上下文和执行bind时一致;
        // this instanceof bind 是在构建函数new 操作时判断是否为 bind的实例;
        // bind之后的函数再执行还会传参,[...args,...args2] 用来整合参数

        return fn.apply(this instanceof bind ? this : context, [...args,...args2]);
    }

    bind.prototype = Object.create(this.prototype);

    return bind;
}

bind解析:

bind函数返回的是一个可执行函数,所以最后 return 了一个函数,此刻返回的函数,在执行的时候,this应该保持和传入对象一致,所以需要使用 apply绑定;

bind需要做到可以接收传参,并将参数传给目标函数,而后再执行时传的参数,要接在之前参数的后边,所以使用[...argus, ...argus2]来进行参数整合;

再对 bind后的对象 执行 new 操作时,this应该指向当前对象,所以在 fn.apply 的第一个参数,做了这样的判断this instanceof bind ? this : context;

bind 执行后返回的函数 修改 prototype 时,不应该影响到 fn.prototype ,两者应该是独立的,所以使用 bind.prototype = Object.create(this.prototype) 隔离开。

猜你喜欢

转载自blog.csdn.net/RedaTao/article/details/107094052
今日推荐