call,apply和bind
作用:改变this的指向
function Person(age) {
this.age = age;
}
var obj = {
};
// Person();
Person.call(obj, 18);
// 这两种执行是一样的,准确来说,上面的那种执行实际上就是下面的那种执行
// 在call传入obj会让Person里面的this全部替换成obj,相当于在最初的时候,Person里面的this全部指向window,现在都有了新的地址,就是obj的,从第二开始传参
本质的一个表现是借用别人的函数实现自己的功能,就像下面的这个例子一样,Student涵盖了Person的全部内容,所以可以这样使用
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade){
// var this = {name : "", age : "", sex : ""}
Person.call(this, name, age, sex);
this.tel = tel;
this.grade = grade;
}
apply和call差不多
不同点:
call传参是按顺序一个一个传,而apply里面只能传一个,而且得是数组,就是直接传一个实参列表,如下
Person.apply(this,[name, age, sex]);
对于以上两个来说,除了改变this指向,还有一个功能是让函数自动执行
第三个方法bind,传参方法和call一样,但是bind的返回值是一个新函数,而且需要手动调用,不会自动执行
简单来说就是bind就是要重新调用一下返回的新函数,他相比call就多了这一个功能
例子如下,
window.color = 'red';
var obj = {
color : 'blue'
}
function test() {
console.log(this.color);
}
var newTest = test.bind(obj);
newTest();//blue
btn.onclick = function () {
this.disabled = true;
setTimeout(function () {
//this指向window
this.disabled = false;
}.bind(this) ,3000)//bind里面的this指向btn
}
call,apply和bind的主要应用场景
- call常用做继承
- apply经常和数组有关系,比如想使用Math里面的函数
- bind不调用函数,但还想改变this指向,比如在定时器里面改变this指向