手写call apply bind函数

114 阅读1分钟

call函数

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

        Function.prototype.myCall = function (thisArg, ...args) {
            const fn = Symbol('fn') //声明一个独有的symbol 属性,防止fn 覆盖已有属性

            thisArg = thisArg || window;    //若没有传入this,默认绑定window对象

            thisArg[fn] = this;  // this指向调用call 的对象,即我们要改变this指向的函数

            const result = thisArg[fn](...args) //执行当前函数

            delete thisArg[fn]; //删除我们声明的fn属性

            return result   //返回执行结果

        }

apply函数

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

    Function.prototype.myApply = function (thisArg, args) {
            const fn = Symbol('fn'); 

            thisArg = thisArg || window; 

            thisArg[fn] = this; 

            const result = thisArg[fn](...args); 

            delete thisArg[fn]; 

            return result;
        }

bind 函数

bind() 方法也改变this指向,但会返回一个新的函数,需要再次调用


    Function.prototype.myBind = function (thisArgs, ...args) {

            const self = this;

            const fn = function () {
                self.apply(this instanceof self ? this : thisArgs, args.concat(Array.prototype.slice.call(arguments)))
            }
n
            fn.prototype = Object.create(self.prototype);

            return fn;
        }

总结

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

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

bind() 方法也改变this指向,但会返回一个新的函数,需要再次调用。