js 实现bind

实现bind

需要注意的是要考虑作为构造函数的case
构造函数会指定this为new出来的实例对象,此时bind指定的目标无效

/**
 * fn.bind(context)
 * Function.bind(this: Function, thisArg: any, ...argArray: any[]): any
 * @param {*} context binding target
 */
Function.prototype._bind = function(context){
    if(typeof this !== 'function' ){
        throw 'Error'
    }
    const _this = this
    const args = Array.from(arguments).slice(1)
    return function F(){
        // if constructor, this.__proto__ -> F.prototype
        if(this instanceof F){
            // new会改变bind的指向,此时context这个参数传进来没有意义
            return new _this(...args,...arguments)
        }
        // 不作为constructor
        return _this.apply(context,[...args,...arguments])
    }   
}

const fn = function(){
    console.log(this)
}
const o = fn._bind({})()
posted @ 2022-01-25 13:00  IslandZzzz  阅读(57)  评论(0编辑  收藏  举报