首页 > 其他 > 详细

手写bind

时间:2021-09-11 13:44:47      阅读:20      评论:0      收藏:0      [点我收藏+]
// _bind.js
// 别人写法
Function.prototype._bind1 = function (context, ...args) {
    if (!context || context === null) context = window;
    const fn = Symbol();
    context[fn] = this;
    const _this = this;
    const result = function (...innerArgs) {
        if (this instanceof _this) {
            this[fn] = _this;
            this[fn](...[...args, ...innerArgs]);
            delete this[fn];
        } else {
            context[fn](...[...args, ...innerArgs]);
            delete context[fn];
        }
    };
    result.prototype = Object.create(this.prototype);
    return result;
};

// 官方写法
Function.prototype._bind2 = function () {
    const _this = this;
    const realThis = arguments[0] ? arguments[0] : window;
    const restParams = arguments && arguments.slice(1);
    if (typeof _this !== ‘function‘) {
        throw new TypeError(‘Function.prototype.bind - ‘ + ‘what is trying to be bound is not callable‘);
    }
    return function () {
        _this.call(realThis, ...restParams);
    };
};

手写bind

原文:https://www.cnblogs.com/tutao1995/p/15252636.html

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