首页 > 移动平台 > 详细

call,apply,bind实现

时间:2021-09-02 21:40:38      阅读:35      评论:0      收藏:0      [点我收藏+]

自定义call方法

Function.prototype.myCall = function (context) {
    if (typeof this !== function){
        throw new TypeError(`${context} is not a function`)
    }
    context = context || window
    context.fn = this
    let args = [...arguments].slice(1)
    let myfn = context.fn(args)
    delete context.fn
    return myfn
}

自定义apply方法

Function.prototype.myApply = function (context) {
    if (typeof this !== ‘function‘){
        throw new TypeError(`${context} is not a function`)
    }
    context = context || window
    context.fn = this
    let myfn
    if (arguments[1]) {
        myfn = context.fn(...arguments[1])
    } else {
        myfn = context.fn()
    }
    delete context.fn
    return myfn
}

自定义bind方法

Function.prototype.myBind = function (context) {
    if (typeof this !== ‘function‘){
        throw new TypeError(`${context} is not a function`)
    }
    const _this = this
    const args = [...arguments].slice(1)
    return function myFn () {
        if (this instanceof myFn) {
            return new _this(...args, ...arguments)
        }
        return _this.apply(context, args.concat(...arguments))
    }
}

参考:

https://juejin.cn/post/6844903764999012366#heading-2

call,apply,bind实现

原文:https://www.cnblogs.com/dropInInt/p/15219655.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!