记录第二次手写apply,call,bind

138 阅读1分钟

1.说说bind、call、apply 区别?手写它们

都是改变this指向,不过bind返回的是一个函数,而apply和call 直接返回结果。

apply的第二个参数接受的是一个数组,而 call 接受的是参数列表

1. Function.prototype.myCall = function (context) {
            var context = context || window
            context.Fn = this
            console.log(context.Fn);
            let args = [...arguments].slice(1)
            const result = context.Fn(...args)
            delete context.Fn
            return result
        }

Function.prototype.myApply = function (context) {
            var context = context || window
            context.Fn = this
            console.log(arguments);
            let result
            if (arguments[1]) {
                if ((arguments[1] instanceof Array)) {
                    result = context.Fn(...arguments[1])
                } else {
                    throw new TypeError('ERROR')
                }
            } else {
                result = context.Fn()
            }
            delete context.Fn
            return result
}

Function.prototype.myBind = function (context, ...args) {
            if (typeof this !== 'function') {
                throw new TypeError('ERROR')
            }
            let self = this
            //bind前后都可以传递参数
            return function F(...arguments) {
                //考虑到bind后返回的函数可以被 new ,所以new后函数的 this 应该指向 new的实例
                if (this instanceof F) {
                    return self.apply(this, [...args, ...arguments])
                }
                return self.apply(context, [...args, ...arguments])
            }
}