跳到主要内容

bind、apply、call 关键字的使用

apply

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

apply() 方法会以给定的 this 值和作为数组(或类数组对象)提供的 arguments 调用该函数。

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

使用 apply() 可以将函数内部的 this 指向任何对象

bind

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

bind()创建一个新函数,当调用该函数时,它会调用原始函数,并将其 this 关键字设置为给定的值, 同时,还可以传入一系列指定的参数,这些参数会插入到调用新函数时传入的参数的前面。

call

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

call() 方法会以给定的 this 值和逐个提供的参数调用该函数。

function Product(name, price) {
this.name = name;
this.price = price;
this.fatherClass = "Product";
// console.log("Product",this);
}

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

console.log(new Food("cheese", 5).fatherClass);
// Expected output: "cheese"

apply、call

相同点:apply()call() 的作用是一直的,都是用于指定函数内部 this 的指向。

区别: apply() 方法接受一个数组作为参数,而 call() 方法接受参数列表。

func.call(this, "eat", "bananas");
func.apply(this, ["eat", "bananas"]);