bind(),call(),apply()三种方法
1.call方法
var o = {
name: '刘浩存'
}
function fn(){
console.log(this);
}
fn.call(o)//改变fn的this指向为对象 o
// 可以继承其他构造函数的属性
function Father(uname, age, sex) {
this.uanme = 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);
在调用我父构造函数的同时,把父构造函数的this指向改成子构造函数的this指向
2.apply方法
1.也是调用函数,第二个可以改变函数内部的this指向
2.但是他的参数必须是数组(伪数组)
var o = {
name: '刘浩存'
}
function fn(xhh) {
this.xhh = xhh;
}
fn.apply(o, ['送你一朵小红花'])
console.log(o);
3.apply的主要应用
// 可以用来求数组里面的最大值和最小值
var arr = [1, 2, 3, 4, 55, 66, 77];
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
console.log(max);
console.log(min);
3.bind方法
1.bind方法不会调用函数,但是能改变函数的this指向
2.返回的是源函数改变之后this产生的新函数
var o = {
name: '刘浩存'
}
function fn() {
console.log(this);
};
var f = fn.bind(o)
f() //刘浩存
3.bind的使用
var btn = document.querySelector('button')
btn.addEventListener('click', function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false;
}.bind(this), 2000)
})
改变了定时器的this指向为按钮,而且让计时器两秒之后调用返回的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<body>
<script>
var btns = document.querySelectorAll('button')
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false;
}.bind(this), 2000)
})
}
</script>
</body>
</html>