call、apply、bind
call、apply、bind区别
call
调用函数并立即执行,逐个传递参数
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // 输出: Hello, Alice!
apply
调用函数并立即执行,以数组形式传递参数
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.apply(person, ['Hello', '!']); // 输出: Hello, Alice!
bind
返回一个新的函数,不会立即执行,参数可以逐个传递或部分预设
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
const greetAlice = greet.bind(person, 'Hello');
greetAlice('!'); // 输出: Hello, Alice!
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 代码有点萌!
评论
ValineDisqus