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

【Handwriting】模拟实现 call, apply #7

Open
Enivia opened this issue Nov 15, 2022 · 0 comments
Open

【Handwriting】模拟实现 call, apply #7

Enivia opened this issue Nov 15, 2022 · 0 comments

Comments

@Enivia
Copy link
Owner

Enivia commented Nov 15, 2022

call

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

语法

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

使用

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = "food";
}

console.log(new Food("cheese", 5).name);
// expected output: "cheese"

实现

Function.prototype.call2 = function (ctx) {
  const context = ctx || window;
  context.fn = this;
  const args = [...arguments].slice(1);
  const res = context.fn(...args);
  delete context.fn;

  return res;
};

apply

apply() 方法调用一个具有给定 this 值的函数,以及以一个数组(或一个类数组对象)的形式提供的参数。

语法

apply(thisArg);
apply(thisArg, argsArray);

使用

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

const min = Math.min.apply(null, numbers);

console.log(min);
// expected output: 2

实现

Function.prototype.apply2 = function (ctx, args) {
  const context = ctx || window;
  context.fn = this;
  const res = args ? context.fn(...args) : context.fn();
  delete context.fn;
  return res;
};

参考:mqyqingfeng/Blog#11

@Enivia Enivia changed the title 模拟实现 call, apply 【Handwriting】模拟实现 call, apply Nov 16, 2022
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