总结
- this指向上一个调用者
- 箭头函数没有this
- call, apply, bind可以改变this指向
- call,apply 改变之后执行一次,bind只改变不执行
- call传对象,apply传数组
代码
<!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>
</body>
<script>
console.log(this)
function a() {
console.log(this)
}
a()
let b = {
userName: 'beizhen',
func: function () {
console.log(this)
}
}
b.func()
const d = {
a: 10,
b: {
a: 20,
func: function () {
console.log(this.a)
}
}
}
d.b.func()
let id = 10
function x() {
setTimeout(() => {
console.log(this.id)
}, 500)
}
x({
id: 20 })
x.call({
id: 20 })
</script>
</html>