美文网首页程序员让前端飞
JavaScript 手写call apply bind

JavaScript 手写call apply bind

作者: 阿毛啊726 | 来源:发表于2020-10-14 19:15 被阅读0次

相同点:call apply bind都是为了改变函数的this指向
不同点:
1)call 参数依次传入
2)apply 参数以数组的方式传入
3)bind 是一个方法,需要用()才能执行,两种传参方法都可以

obj.myFun.call(db,'成都','上海');  // 德玛 年龄 99  来自 成都去往上海
obj.myFun.apply(db,['成都','上海']);  // 德玛 年龄 99  来自 成都去往上海  
obj.myFun.bind(db,'成都','上海')();    // 德玛 年龄 99  来自 成都去往上海
obj.myFun.bind(db,['成都','上海'])();  // 德玛 年龄 99  来自 成都, 上海去往 

手写实现#

call

    Function.prototype.myCall = function(context) {
        if(typeof this !="function"){
            throw new TypeError()
        }
        //如果没有传参,绑定window
        context=context||window
        // 改变this的指向
        context.fn=this
        //获得参数
        const args=[...arguments].slice(1)
        //执行这个方法
        const result=context.fn(...args)
       //删除我们声明的fn属性 
        delete context.fn
        return result
    }

apply

Function.prototype.myApply = function(context) {
        if (typeof this !== 'function') {
            throw new TypeError('Error')
        }
        context = context || window
        context.fn = this
        let result
        // 处理参数和 call 有区别
        if (arguments[1]) {
            result = context.fn(...arguments[1])
        } else {
            result = context.fn()
        }
        delete context.fn
        return result
    }

bind

    Function.prototype.myBind = function (context) {
        if (typeof this !== 'function') {
            throw new TypeError('Error')
        }
        const _this = this
        const args = [...arguments].slice(1)
        // 返回⼀个函数
        return function F() {
            // 因为返回了⼀个函数,我们可以 new F(),所以需要判断
            if (this instanceof F) {
                return new _this(...args, ...arguments)
            }
            return _this.apply(context, args.concat(...arguments))
        }
    }
    f.say.myCall(fn,"call","y")//namecally
    f.say.myApply(fn,["apply","y"])//nameapplyy
    f.say.myBind(fn,"bind","y")()//fnbindy

相关文章

网友评论

    本文标题:JavaScript 手写call apply bind

    本文链接:https://www.haomeiwen.com/subject/ilnwpktx.html