Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS实现apply方法 #29

Open
mtonhuang opened this issue Dec 22, 2020 · 0 comments
Open

JS实现apply方法 #29

mtonhuang opened this issue Dec 22, 2020 · 0 comments

Comments

@mtonhuang
Copy link
Owner

mtonhuang commented Dec 22, 2020

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

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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant