mqyqingfeng / Blog

冴羽写博客的地方,预计写四个系列:JavaScript深入系列、JavaScript专题系列、ES6系列、React系列。
30.53k stars 4.7k forks source link

感觉还是要把中间那个对象处理一下更好 #264

Open NoAlligator opened 2 years ago

NoAlligator commented 2 years ago
Function.prototype.__bind__ = function (context = window, ...args_front) {
    if (typeof this !== 'function') throw new TypeError('You can not use call() at a non-function')
    const fSelf = this
    const fEmpty = function () {
    }
    const fBound = function (...args_back) {
        if (this instanceof fEmpty) {
            Object.setPrototypeOf(this, fSelf.prototype) //重新指向源构造函数
            return fSelf.apply(this, ...args_front.concat(args_back))
        }
        return fSelf.apply(context, ...args_front.concat(args_back))
    }
    fEmpty.prototype = fSelf.prototype
    fBound.prototype = new fEmpty()
    return fBound
}