# call

this 章节,我们了解了当我们明确绑定对象环境的时候,需要使用 call 来绑定。(具体为啥使用看 this 章节)。

  1. 实现一个简易版的。
if (!Function.prototype.call) {
    Function.prototype.call = function (context, ...args) {
        context.fn = this;
        const result = context.fn(...args);
        delete context.fn;
        return result;
    }
}

  1. 当我们传入 null、undefined、empty 是会绑定到 window 上,而 字符串、数字、布尔值回绑定到包装对象上的。
if (!Function.prototype.call) {
    Function.prototype.call = function (context, ...args) {
        context = context ? Object(context) : window;
        context.fn = this;
        const result = context.fn(...args);
        delete context.fn;
        return result;
    }
}
  1. ES6 之前是没有rest参数和扩展运算符的。
if (!Function.prototype.call) {
    Function.prototype.call = function (context) {
        context = context ? Object(context) : window;
        context.fn = this;
        var args = [];
        for (var i = 1; i < argument.length; i++) {
            args.push('argument[' + i + ']');
        }
        var result = eval('context.fn(' + args + ')');
        delete context.fn;
        return result;
    }
}