// 使用 call 方法
function greet(greeting, punctuation) {
console.log(greeting + ' ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // 输出: Hello Alice!
// 使用 apply 方法
function introduce(adjective1, adjective2) {
console.log(`I am ${this.name}, I'm ${adjective1} and ${adjective2}.`);
}
introduce.apply(person, ['brave', 'smart']); // 输出: I am Alice, I'm brave and smart.
// 使用 bind 方法
function farewell(goodbye) {
console.log(goodbye + ', ' + this.name);
}
const sayGoodbye = farewell.bind(person, 'Goodbye');
sayGoodbye(); // 输出: Goodbye, Alice
call 方法:调用一个函数,并将函数内部的 this 指向指定的对象,同时可以传递参数。参数以逗号分隔的形式传入。apply 方法:与 call 类似,但它接受一个参数数组(或类数组对象)来传递给函数。bind 方法:创建一个新的函数,在调用时设置这个新函数的 this 值为提供的值,并且可以预设部分参数。返回的新函数可以在之后被调用。上一篇:js 对象转map
下一篇:js switch 用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站