call、apply、bind有什么区别?

terry Javascript 269

Call、Apply 和 Bind 之间的区别可以用下面的例子来解释

call: call() 方法调用一个函数,给定的this值和参数一一提供

var employee1 = {firstName: 'Haiyong', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.call(employee1, 'Hello', 'How are you?'); // Hello Haiyong Rodson, How are you?
invite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

apply:调用具有给定this值的函数,并允许你将参数作为数组传入

var employee1 = {firstName: 'Haiyong', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.apply(employee1, ['Hello', 'How are you?']); // Hello Haiyong Rodson, How are you?
invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?

bind:返回一个新函数,允许你传递任意数量的参数

var employee1 = {firstName: 'Haiyong', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1('Hello', 'How are you?'); // Hello Haiyong Rodson, How are you?
inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

Call 和 apply 可以互换。两者都立即执行当前函数。你需要决定是发送数组还是逗号分隔的参数列表更容易。你可以通过处理 Call 用于逗号(分隔列表)和 Apply 用于Array来记住。

而 Bind 创建一个新函数,该函数将this设置为传递给 bind() 的第一个参数。

  • 暂无回复内容