改变函数内this指向 js提供了三种方法 call() apply() bind()
共同点 : 都可以改变this指向
不同点:1. call 和 apply 会调用函数, 并且改变函数内部this指向
2. call 和 apply传递的参数不一样,call传递参数使用逗号隔开,apply使用数组传递
3 .bind 不会调用函数, 可以改变函数内部this指向
应用场景:
1. call 经常做继承
<body>
<script>
var o = {
name: 'andy'
}
function fn(a, b) {
console.log(this);
console.log(a + b);
};
fn.call(o, 1, 2);
// call 第一个可以调用函数 第二个可以改变函数内的this 指向
// call 的主要作用可以实现继承
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);
}
var son = new Son('刘德华', 18, '男');
console.log(son);
</script>
</body>
2. apply经常跟数组有关系. 比如借助于数学对象实现数组最大值最小值
<body>
<script>
// apply 调用函数 改变函数内this的指向
// 求数组最大值
// var arr = [10, 20, 30, 13];
// var max = arr[0];
// for (var i = 1; i < arr.length; i++) {
// if (max < arr[i]) {
// max = arr[i];
// };
// };
// console.log(max);
var arr = [10, 20, 30, 13];
var max = Math.max.apply(Math, arr);
//这句代码的意思执行Math对象中的max函数,参数为arr,并将返回结果赋值于max
// 其中apply 函数为JS的内置函数,作用为执行该函数。且只能被函数调用。
// apply函数中的第一个参数为函数所属对象,通常为当前页面(this)。第二个参数为传入到函数中的参数数组(必须为数组)
console.log(max);
</script>
</body>
3. bind 不调用函数,但是还想改变this指向. 比如改变定时器内部的this指向
<body>
<button>点击1</button>
<button>点击2</button>
<button>点击3</button>
<script>
// bind() 绑定 捆绑的意思
// 获取元素
var btns = document.querySelectorAll('button');
// 给所有button注册点击事件
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
// 当前被点击的按钮设置为禁用
this.disabled = true;
// 三秒以后设置为不禁用的效果 需要延时器
setTimeout(function () {
// 想要在这里找到被点击的那个按钮,需要改变这个里面的this指向,因为延时器里面this是指向window的,而且不能点击就调用函数,必须三秒之后,所以用bind改变函数this指向
this.disabled = false;
}.bind(this), 3000)
};
};
</script>
</body>