码迷,mamicode.com
首页 > 移动开发 > 详细

JS模拟实现call、apply、bind

时间:2020-05-19 13:03:03      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:cal   ext   bsp   slice   属性   arguments   返回   window   code   

function call_mock (obj) {
    var aim_fun = this;
    var argument = [];
    for (var i = 1; i < arguments.length; i++) {
        argument.push(arguments[i]);
    }
    obj.aim_fun = aim_fun;
    var result = eval(‘obj.aim_fun(‘+ argument.join() + ‘)‘);
    delete obj.aim_fun;
    return result;
}

Function.prototype.call_mock = call_mock;

function apply_mock (obj, args) {
    var aim_fun = this;
    obj.aim_fun = aim_fun;
    var result = eval(‘obj.aim_fun(‘+ args.join() + ‘)‘);
    delete obj.aim_fun;
    return result;
}

Function.prototype.apply_mock = apply_mock;

function bind_mock (obj) {
    var aim_fun = this;
    var argument = [];
    for (var i = 1; i < arguments.length; i++) {
        argument.push(arguments[i]);
    }
    var fNOP = function () {};
    var fBound = function () {
        return aim_fun.apply_mock(obj, argument)
    }
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

Function.prototype.bind_mock = bind_mock;

var a = {
    c:1,
    see(a, b) {
        console.log(`${this.c}${a}${b}`);
    }
}

c = 0;

a.see.bind_mock(global, 1, 2);

 ------------------------------------------

Function.prototype.mycall = function(context) {
    var context = context || window;
    // 给context添加一个属性
    context.fn = this;
    // 获取参数
    var args = [...arguments].slice(1);
    // 执行该函数
    var result = context.fn(...args);
    // 删除fn    
    delete context.fn;
    // 返回执行结果
    return result;
}

Function.prototype.myapply = function(context) {
    var context = context || window;

    context.fn = this;

    var result = null;

    if(arguments[1]) {
    
        result = context.fn(...arguments);
        
    }else {
    
        result = context.fn();
        
    }
    
    delete context.fn;

    return result;
}

Function.prototype.mybind = function(context) {
    if(typeof this !== ‘function‘) {
    
        throw new TypeError(‘Error‘);
        
    }
    
    var _this = this;

    var args = [...arguments].slice(1);

    return function F() {
    
        if(this instanceof F) {
        
            return new _this(...args, ...arguments);
            
        }
        
        return _this.apply(context, args.concat(...arguments));
        
    }
}

 

JS模拟实现call、apply、bind

标签:cal   ext   bsp   slice   属性   arguments   返回   window   code   

原文地址:https://www.cnblogs.com/ckAng/p/12915917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!