手写bind方法

Function.prototype.myBind = function () {
    // 函数本体
    const fn = this;
    
    // this指向
    const context = arguments[0]
    // 参数
    const args = Array.prototype.slice.call(arguments, 1)

    // 新函数
    return function newFn() {

        // 新函数参数
        const newArgs = Array.prototype.slice.call(arguments)

        // 当作构造函数使用
        if (this instanceof newFn) {
            return new fn(...args.concat(newArgs))
        }

        // 单座普通函数使用
        return fn.apply(context, args.concat(newArgs))
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容