首页 > 其他 > 详细

自定义bind

时间:2020-06-22 23:36:39      阅读:80      评论:0      收藏:0      [点我收藏+]
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

自定义bind

原文:https://www.cnblogs.com/peaky/p/bind.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!