mtonhuang / blog

博客,想法,笔记

Home Page:http://huangmiantong.cn/ (已废弃)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JS实现apply方法

mtonhuang opened this issue · comments

以下内容参考 冴羽大神的文章

call的定义是什么?

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数或方法。

语法

function.call(thisArg, arg1, arg2, ...)

用法

var foo = {
    value: 1
};

function bar() {
    console.log(this.value);
}

bar.call(foo); // 1

可以看到:

  • call 改变了 this 的指向,指向到 foo
  • bar 函数执行了

理解它

var foo = {
    value: 1,
    bar: function() {
        console.log(this.value)
    }
};

foo.bar(); // 1

实现原理

  • 将函数设为对象的属性
  • 执行该函数
  • 删除该函数
    Function.prototype.callAl = function (context) {
      // 判断是否传入null 或者 undefined,如果是,则指向window
      var context = context || window;
      context.fn = this;
      var arr = [];
      // 遍历参数
      for (var i = 1, total = arguments.length; i < total; i++) {
        arr.push(arguments[i]);
      }
      var result = context.fn(...args);
      // 删除context对象原本没有的fn函数
      delete context.fn;
      return result;
    };
    var value = 'I am window';
    var obj = {
      value: 'I am obj value',
    };
    var bar = function (name, age) {
      console.log(this.value);
      return {
        value: this.value,
        name: name,
        age: age,
      };
    };
    bar.callAl(null);
    bar.callAl(obj, 'mton', '24');