自定义bind

Function.prototype.mybind = function (context, ...args1) {
    // 判断是否为函数
    if (typeof this !== 'function') {
        throw new Error('Error');
    }
    // 默认绑定对象为window
    context = context === undefined ? window : context;
    // 指向函数的this
    _this = this;
    return function (...args2) {
        return _this.apply(context, args1.concat(args2));
    }
}

var name = 'window';

var hello = {
    name: 'hello',
    fn() {
        console.log(this.name);
        console.log(...arguments);
    }
}

var world = {
    name: "world"
}

hello.fn.mybind(world, 1, 2, 3)(4);

执行结果:
world
1 2 3 4

猜你喜欢

转载自www.cnblogs.com/peaky/p/bind.html