一、call()
1、调用函数
fn.call();
2、改变this指向 call(thisArg,x1,x2)
thisArg this要指向谁
x1,x2传递的参数(可选,没有就不写)
调用fn函数,并且把this指向o
function fn(x, y) {
console.log('我想喝手磨咖啡');
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
};
fn.call(o, 1, 2);
3、继承
// 1. 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
// 2 .子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
Father.call(this, uname, age);
this.score = score;
}
var son = new Son('刘德华', 18, 100);
console.log(son);
在Son中,利用call调用Father函数,并把this指向Son中的this,这样就继承了Father的属性
二、apply(thisArg,['x'])
1、调用函数
2、第二个可以改变函数内部的this指向
3、 但是他的参数必须是数组(伪数组)
例如:利用Math.max求最大最小值
var arr = [1, 66, 3, 99, 4];
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
此处this不用指向谁,可以为null,但是在严格模式下会报错,因此我们可以指向Math对象
三、bind(thisArg,x1,x2)常用
1、不调用函数
2、返回值是原函数改变this之后产生的新函数
3、使用场景:如果有的函数我们不需要立即调用,但是又想改变这个函数内部的this指向此时用bind
案例:我们有很多按钮,当我们点击了之后,就禁用这个按钮,3秒钟之后开启这个按钮
此处我们没有立即调用函数,因为要交由定时器负责调用,但是此处我们改变了this指向;
我们在定时器函数外面bind(this),但是还在btns[i].οnclick=function(){}里面,所以相当于把定时器里的this指向了外面btns[i]
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);
}
}