首先call、apply、bind的作用都是改变函数运行时this的指向。其次,在 ES6 的箭头函数下, call 和 apply、bind 将失效。
一、参数区别
1、call 方法第一个参数是要绑定给this的值,后面传入的是一个参数列表,当第一个参数为null、undefined的时候,默认指向window。比如:
Fun.call(obj,'arg1', 'arg2')
2、apply接受两个参数,第一个参数是要绑定给this的值,第二个参数是一个参数数组。当第一个参数为null、undefined的时候,默认指向window。比如:
Fun.apply(obj,['arg1', 'arg2'])
3、bind接受两个参数,第一个参数是要绑定给this的值,第二个参数是一个参数数组,这一点与apply相同。
二、调用区别
1、call、apply都是立即调用。bind 方法不会立即执行,而是返回一个改变了上下文 this 后的函数,便于稍后调用。而原函数 中的 this 并没有被改变,依旧指向原来该指向的地方。
function fn(a, b, c) {
console.log(a, b, c);
}
var fn1 = fn.bind(null, 'Dog');
fn('A', 'B', 'C'); // A B C
fn1('A', 'B', 'C'); // Dog A B
fn1('B', 'C'); // Dog B C
fn.call(null, 'Dog');
var obj = {
message: 'My name is: '
}
function getName(firstName, lastName) {
console.log(this.message + firstName + ' ' + lastName)
}
getName.apply(obj, ['Dot', 'Dolby'])// My name is: Dot Dolby
bind应用场景:给参数指定默认参数、绑定构造函数