call方法
call函数的作用有两个:一是可以调用函数,二是改变函数内的this指向。主要作用是可以实现继承。
function Father (uname, age, sex) {
this.uname = uname;
this.age = age;
this.sex = sex;
}
function Son (uname, age, sex) {
Father.call(this,uname, age, sex); //参数中的this将指向Father函数创建的实例改为指向Son创建的实例
// Father(uname, age, sex);//此方式Son实例不会继承Father构造函数的属性
}
let son = new Son('lee', 23, '女');
构造函数Son继承了Father构造函数中的属性。
2、apply方法
该函数可以调用一个函数,也可以改变函数的this指向,调用方式如下
fun.apply(thisArg, [argsArray])
- thisArg: 表示this新指向的对象,也就是将来调用fun方法的对象
- argsArray: 传递给函数fun的值,以数组的形式存放
- 返回值就是函数的返回值,因为他就是调用函数
//借助于apply和数学内置对象求最大值
let arr = [1,66,3,99,4];
let max = Math.max.apply(Math, arr);
bind函数
bind函数不会调用函数,但能改变内部this的指向
fun.bind(thisArg, arg1, arg2, ...)
- thisArg: 在fun函数运行时指定的this值
- arg1,arg2:传递的参数
- 返回由指定的this值和初始化参数改造的新函数
let o = {
name: 'andy';
};
function fn() {
console.log(this);
}
let f = fn.bind(o);
f();
当我们不需要立即调用函数,但又想改变这个函数内部的this指向时,用bind函数,假设现在有一个按钮,当我们点击之后就禁用这个按钮,3秒后重新开启这个按钮,当不使用bind函数时,实现方式如下:
var btn = document.querySelector('button');
btn.onclick = function() {
this.disabled = true; //该this指向的是btn这个按钮
var that = this;
setTimeout(function() {
that.disabled = false; //此处用不用this的原因是,定时器内部的this指向windows,但是我们是为按钮对象设置disabled属性,所以要将定时器外面的this指向存储到that中
},3000)
}
使用bind函数时,实现代码如下:
var btn = querySelector('button');
btn.onclick = function () {
this.disabled = true;
setTimeout({
this.disabled = false;
}.bind(this), 3000) //这个this在定时器函数的外面,指向btn这个对象
}
主要应用场景
1、call经常用于继承场景
2、apply与数组有关系,比如借助于数学对象实现数组的最大值最小值
3、bind不立即执行函数,但是还想改变this指向,比如改变定时器内部的this指向