加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

替换this的调用方式

发布时间:2020-12-14 05:09:31 所属栏目:大数据 来源:网络整理
导读:原生实现 call 方法 Function.prototype.callback = function(firstarg,...args) { if (!firstarg) { firstarg = typeof window === ‘undefined‘ ? ‘global‘ : ‘window‘; } firstarg.func = this; let res = null; if (args) { res = firstarg.func(ar

原生实现 call 方法

Function.prototype.callback = function(firstarg,...args) {
    
    if (!firstarg) {
        firstarg = typeof window === ‘undefined‘ ? ‘global‘ : ‘window‘;
    }
    firstarg.func = this;
    let res = null;

    if (args) {
        res = firstarg.func(args);
    } else {
        res = firstarg.func();
    }
    
    delete firstarg.func;
    return res;
}

原生实现 apply 方法

Function.prototype.apply = function(firstArg,arr) {
    if (arr && Object.prototype.toString.call(arr) !== ‘[object Array]‘) {
        throw new Error(‘第二个参数应为数组‘);
    }
    if (!firstarg) {
        firstarg = typeof window === ‘undefined‘ ? ‘global‘ : ‘window‘;
    }
    firstarg.func = this;
    let res = null;
    
    if (arr.length>0) {
        res = eval(‘firstarg.func(‘+arr.join(‘,‘)+‘)‘);
    } else {
        res = firstarg.func();
    }
    return res;
}

原生实现 bind 方法

Function.prototype.bind = function (ctx,...formerArgs) {
    const _this = this;
    return (...laterArgs) => {
        return _this.apply(ctx,formerArgs.concat(laterArgs));
    }
}**就是这么简单**

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读