call、apply作用:
调用函数,改变函数的this指向
bind作用:
不会调用函数,改变函数this指向,返回原函数改变this之后产生的新函数
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
};
fn.call(o, 1, 2);
// 此时这个函数的this 就指向了o这个对象,1、2当形参传递
fn.apply(o,[1,2]) //参数使用数组传递 运行结果为3
call实现继承
function Father(name, age) {
this.name = name;
this.age = age;
}
Father.prototype.money = function() {
console.log('father earns money');
}
function Son(name, age, score) {
Father.call(this, name, age);
// this 指向子构造函数的对象实例
//把father中this指向son里面this
this.score = score;
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
// 重新指回原来的构造函数
Son.prototype.exam = function() {
console.log('son needs exam')
}
var xiaoming = new Son('xiaoming', '18', '90')
xiaoming.exam() //son needs exam
xiaoming.money() //father earns money
call添加数组
let arr1 = ['1', '2'];
(function() {
Array.prototype.push.call(arguments, '王五');
console.log(arguments);
})(arr1)
// 0: Array(2) ["1", "2"]
// 1: "王五"
apply合并数组
let arr1=[1,2,3];
let arr2=[4,5,6];
Array.prototype.push.apply(arr1,arr2); //将arr2合并到了arr1中
apply求数组最大值
var arr = [1, 66, 3, 99, 4];
var max = Math.max.apply(Math, arr);
var max1 = Math.max.apply(null, arr);
bind实用
var btns = document.querySelectorAll('button');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false;
}.bind(this), 2000); //2秒后解除按钮禁用
}
} //让定时器里面的this指向btn
bind改变this指向
var name = '李四'
var foo = {
name: "张三",
logName: function(age) {
console.log(this.name, age);
}
}
foo.logName(8) //张三 8
var fooNew = foo.logName;
fooNew(10) //李四,10
var fooNewBind = foo.logName.bind(foo);
fooNewBind(11) //张三,11 因为bind改变了fooNewBind里面的this指向