// 示例代码:使用 call 和 apply 方法
function greet(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called in the context of ${this}.`);
}
const person = { name: 'Alice', age: 30 };
// 使用 call 方法
greet.call(person, 'Bob', 25);
// 输出: Hello, my name is Bob and I am 25 years old. This function was called in the context of [object Object]
// 使用 apply 方法
greet.apply(person, ['Charlie', 40]);
// 输出: Hello, my name is Charlie and I am 40 years old. This function was called in the context of [object Object]
// 解释说明:
// call 和 apply 都可以改变函数的 this 指向,并立即调用函数。
// 主要区别在于传递参数的方式:
// - call 方法接受的是参数列表,直接将参数依次传入。
// - apply 方法接受的是一个参数数组,将数组作为参数传入。
上一篇:js 深拷贝对象
下一篇:js alter
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站