bind, call, apply
call, apply, bind三种方法都可以用来改变当前函数的this指向。
先说区别
传参
1.第一个参数都是要更改调用的对象,不传递则默认指向window。
2.第二个及后续参数,call和bind相似,参数可以有多个,依次传入,apply只有两个参数,第二个参数必须是数组。
调用
call和apply调用后会自动执行调用的函数,bind会返回一个新的函数,并需要自动调用
let person = {
name: "张三",
age: 18,
show(age) {
console.log('年龄是' + age || this.age);
}
}
let person2 = {
name: '李四',
}
person.show.call(person2, 22); // 年龄是22
person.show.apply(person2, [23]); // 年龄是23
person.show.bind(person2, 24)(); // 年龄是24
使用案例
1.拼接数组
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
// 使用concat方法
var arr = arr1.concat(arr2);
console.log(arr); // [1, 2, 3, 4, 5, 6]
// 使用扩展运算符
var arr3 = [...arr1, ...arr2]
console.log(arr3); // [1, 2, 3, 4, 5, 6]
// 使用apply
Array.prototype.push.apply(arr1, arr2);
console.log(arr1) // [1, 2, 3, 4, 5, 6]
2.实现继承
function Father(name, age) {
this.name = name;
this.age = age;
this.address = '三里屯';
this.show = function() {
console.log('姓名' + this.name + ',年龄' + this.age + ',籍贯' + this.address);
}
}
function Son(name, age) {
Father.call(this, name, age);
}
var son = new Son("儿子", 13);
son.show(); // 姓名儿子,年龄13,籍贯三里屯
3.类数组调用数组的方法
let doms = document.getElementsByClassName('box');
Array.prototype.forEach.call(doms, function(f) {});
4.求数组的最大值
let arr = [1, 34, 23, 432, 123];
Math.max.apply(null, arr); // 432