<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<script>
var o = {
name: 'ht'
}
// call()
function fn(a, b) {
console.log(this);
console.log(a + b);
}
fn.call(o, 1, 2) //第一个参数为this指向
//apply() 以数组形式传参
var arr = [1, 4, 3, 6, 9];
function fn2(myarr) {
console.log(this);
console.log(myarr);
}
fn2.apply(o, arr); //1
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
console.log(max, min);
//bind()
//不会立即调用,结果返回一个新的函数
//通过bind方法返回的函数,不能再通过call/apply/bind改变内部的this指向了
var btns = document.querySelectorAll('button');
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function () {
setTimeout(function () {
this.disabled = true;
}.bind(this), 3000)
})
}
function fn3(a, b, c, d) {
console.log(a, b, c, d);
}
//如果在绑定时,没有把所有参数都绑定,那么剩下的参数可以在调用时再设置值,绑定了的参数,不能再修改
var f = fn3.bind(o, 1, 2);
f(); //1 2 undefined undefined
f(3, 4) //1 2 3 4
</script>
</body>
</html>
改变this指向---call(),apply(),bind()
最新推荐文章于 2022-04-16 22:05:39 发布