手写call,apply,bind

92 阅读1分钟

1.call

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

function.call(thisArg, arg1, arg2, ...)

注意:该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。

手写实现:

    Function.prototype.myCall = function(target, ...args) {
        if (typeof this !== "function")  return
        target = target || window
        target.fn = this       // 改变this 指向
        let result = target.fn(...args)
        return result
  }
    

2.apply

apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。

function.call(thisArg, [arg1, arg2, ...])

手写实现

 Function.prototype.myapply = function(target, args) {
        if (typeof this !== "function")  return
        if (!Array.isArray(args)) return
        target = target || window
        target.fn = this       // 改变this 指向
        let result = target.fn(args)
        return result
    }

3.bind

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

Function.prototype.myBind = function (context) {
    let self = this;
    arr = Array.prototype.slice.call(arguments, 1)
    o = function () { }
    newf = function () {
        let arr2 = Array.prototype.slice.call(arguments)
        arrSum = arr.concat(arr2)
        if (this instanceof o) {
            self.apply(this, arrSum);
        } else {
            self.apply(context, arrSum);
        }
    }
    o.prototype = self.prototype
    newf.prototype = new o
    return newf
};