// 使用 call 方法
function greet(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}
const obj = { name: 'Alice' };
greet.call(obj, 'Bob', 30);
// 输出: Hello, my name is Bob and I am 30 years old. This function was called by Alice.
// 使用 apply 方法
function greetWithApply(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}
greetWithApply.apply(obj, ['Charlie', 25]);
// 输出: Hello, my name is Charlie and I am 25 years old. This function was called by Alice.
// 使用 bind 方法
function greetWithBind(name, age) {
console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}
const boundGreet = greetWithBind.bind(obj, 'David', 35);
boundGreet();
// 输出: Hello, my name is David and I am 35 years old. This function was called by Alice.
call
方法:立即调用函数,并将指定的对象作为 this
上下文传递给函数,同时可以传递参数列表。apply
方法:与 call
类似,但参数是以数组的形式传递。bind
方法:创建一个新的函数,并将指定的对象作为 this
上下文绑定到该新函数上。新函数可以在稍后的时间点被调用。以上代码展示了如何使用 call
、apply
和 bind
来改变函数的 this
上下文并传递参数。
上一篇:js gzip
下一篇:js apply call
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站