EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

bind简单实现 #4

Open EdwardZZZ opened 7 years ago

EdwardZZZ commented 7 years ago

看到一个微博说bind如何实现,想了一个简单实现的方法

// 不使用call / apply,仅支持非null的object绑定
Function.prototype.bind = function(context, ...bindParams) {
    if(!context || typeof context !== 'object') return this;
    var self = this;
    return function bound(...args) {
        context.__fn = self;
        context.__fn(...bindParams, ...args);
        delete context.__fn;
    };
}

// 标准实现
Function.prototype.bind = function(oThis) {
    if (typeof this !== "function") {
        // closest thing possible to the ECMAScript 5
        // internal IsCallable function
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP = function() {},
        fBound = function() {
            return fToBind.apply(this instanceof fNOP ?
                this :
                oThis || this,
                aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
};