代码分析
<!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>Document</title>
</head>
<body>
<script>
let age = 22
// var age = 22
console.log(age)
let obj = {
name: 'John',
age: 18,
say: () => {
//你会发现 this 是 window
console.log(this)
console.log(this.age)
},
say2() {
//毫无疑问,this指向的是当前的obj对象
console.log(this.age)
},
say3() {
setTimeout(function () {
console.log(this)
//你会发现,虽然是普通的函数,在这个定时器中是拿不到这对象中的 name 和 age
console.log(`my name is ${this.name} , my age is ${this.age}`)
}, 500)
},
}
obj.say()
obj.say2()
obj.say3()
</script>
</body>
</html>
输出结果
分析
say: () => {
//你会发现 this 是 window
console.log(this)
console.log(this.age)
},
对于箭头函数,this是没有上下文指向的,它指向的都是整个最外层的对象。这里指向window,由于被let声明的变量age不会作为全局对象window的属性,所以this.age输出为undefined。
say2() {
//毫无疑问,this指向的是当前的obj对象
console.log(this.age)
},
普通的函数,它的this永远都是跟着它上下文走的。this指向的是当前的obj对象,this.age=18。
say3() {
setTimeout(function () {
console.log(this)
//你会发现,虽然是普通的函数,在这个定时器中是拿不到这对象中的 name 和 age
console.log(`my name is ${this.name} , my age is ${this.age}`)
}, 500)
},
setTimeout中所执行函数中的this,永远指向window!!注意是要延迟执行的函数中的this哦!!window没有name 和 age属性值。