apply() 方法的作用与 call() 方法相同。不同之处在于 apply() 方法接受作为数组的参数。
例如:
const person = {
name: 'John'
}
function greet(greeting, message) {
return `${greeting} ${this.name}. ${message}`;
let result = greet.apply(person, ['Hello', 'How are you?']);
console.log(result);
输出:
Hello John. How are you?
在行中:
在greet()函数中,‘Hello’被分配给greeting,‘How are you?’被分配给message。
apply() 方法的作用与 call() 方法相同。不同之处在于 apply() 方法接受作为数组的参数。
例如:
const person = {
name: 'John'
}
function greet(greeting, message) {
return `${greeting} ${this.name}. ${message}`;
}
let result = greet.apply(person, ['Hello', 'How are you?']);
console.log(result);
输出:
Hello John. How are you?
在行中:
let result = greet.apply(person, ['Hello', 'How are you?']);
在greet()函数中,‘Hello’被分配给greeting,‘How are you?’被分配给message。