手写 call apply bind

494 阅读1分钟

call

> 调用方法:fnA.call(obj, arg1, arg2...),作用:修改函数fnA的this指向obj,执行fnA并返回其执行结果

Function.prototype.myCall = function(context = window, ...args) {
    context = context || window;
    context.fn = this;
    var result = context.fn(...args);
    delete context.fn;
    return result;
};

apply

> 调用方法:fnA.apply(obj, [arg1, arg2...]),作用:修改函数fnA的this指向obj,执行fnA并返回其执行结果

Function.prototype.myApply = function(context = window, args = []) {
    context = context || window;
    context.fn = this;
    var result = context.fn(...args);
    delete context.fn;
    return result;
};

bind

> 调用方法:fnA.bind(obj, arg1, arg2...),作用:修改函数fnA的this指向obj,返回修改了this指向后的新函数(注意:和call类似,只是bind不执行返回的新函数)

Function.prototype.myBind = function(context, ...args) {
    var _this = this;
    return function() {
        return _this.myApply(context, args);
    };
};

测试用例

var obj = {
    a: 10,
    b: 20
};
function test(key1, key2) {
    console.log(this[key1] + this[key2]);
}
test.myCall(obj, "a", "b"); // 30a
test.myApply(obj, ["a", "b"]); // 30
test.bind(obj, "a", "b")(); // 30