bind、call、apply

142 阅读1分钟

call实现:

思路:可以给新的对象添加一个函数,然后在执行完以后删除。

Function.prototype.myCall = function(context){
    // 不传入第一个参数,默认为window
    var context = context || window;
    //给新的对象添加一个函数,this指向一个函数
    context.fn = this;
    //arguments为Call里面的参数
    var args = [...arguments].slice(1);
    var result = context.fn(...args);
    delete context.fn;
    return result;
};
function sayName(){
    console.log(this.name);
}
var obj = {
    name:'kimi',
    age:26,
    work:'web'
};
sayName.myCall(obj,'age');

apply实现:

Function.prototype.myApply = function(context){
    var context = context || window;
    context.fn = this;
    var result;
    //判断是否存在第二个参数,如果存在,就将第二个参数展开
    if(arguments[1]){
        result = context.fn(...arguments[1]);
    }else{
        result = context.fn();
    }
    delete context.fn;
    return result;
};

bind:该方法会返回一个函数。

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.concat(...arguments));
        }else{
            return _this.apply(context,args.concat(...arguments));
        }
    }
};