改变this指向 js提供了3种方法 call bind apply
1. call
改变this指向 可以立即调用函数 参数一 this指向谁写谁 参数二:用逗号隔开
场景:用作继承
2.apply
改变函数的this指向 立即调用函数 参数:改变this指向的参数 参数二:数组
形参特点:实参数组有几个元素,就要写有几个形参接收,如果写一个形参就只能接收数组中第一个元素
场景:主要用于处理数组
3.bind(常用)
bind 不会调用函数,但是可以改变题this指向,会返回一个改变this指向后的新函数 参数一 this指向谁写谁 参数二:用逗号隔开
不想调用函数又想改变this指向
案列:
//在script上面有个button按钮
var btn = document.querySelector('button')
btn.addEventListener('click', function () {
this.disabled = true
setTimeout(function () {
this.disabled = false
}.bind(this), 2000)
})
总结:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>this指向总结</title>
</head>
<body>
<button>点击</button>
<script>
// this指向总结
// 1. 普通函数
// 1.1 全局内调用
function fn() {
console.log(this) // window
}
fn()
// 1.2 对象内调用
const obj = {
name: '张三',
sayHi() {
console.log(this) // obj
}
}
obj.sayHi()
// 1.3 构造函数内this
function Person() {
this.name = name
console.log(this)
}
const zs = new Person()
// 1.4 事件处理函数中的this
document.querySelector('button').addEventListener('click', function () {
console.log(this)
})
// 1.5 特殊调用 call apply bind 可以改变this指向
const o = { name: '李四' }
function fun() {
console.log(this)
}
fun.call(o)
// 2. 箭头函数 没有this,是沿用上一级作用域的this
</script>
</body>
</html>