想请老师分析下这道题,不太明白为什么第二个输出是undefined

来源:6-3 什么是闭包?闭包会用在哪里?

December_Hong

2020-12-09

function A() {
    let a = 3
    this.a = 4
    setTimeout(function() {
        console.log(a)
    },100)
    setTimeout(function() {
        console.log(this.a)
    },200)
    setTimeout(() => {
        console.log(a)
    },300)
    setTimeout(() => {
        console.log(this.a)
    },400)
}
new A()
写回答

2回答

双越

2020-12-09

解答:第二个输出的是 undefined

你可以在第一行代码之前插入 var a = 100; 或者 window.a = 100; 

然后在执行所有的代码,你会发现第二个输出的是 100 。

即,第二个 this 指向的是 window ,this.a 即 window.a 。

当 window.a 未定义时,就会输出 undefined

var a = 100;
function A() {
    let a = 3
    this.a = 4
    setTimeout(function() {
        console.log(1, a)
    },100)
    setTimeout(function() {
        console.log(2, this.a) // 100
    },200)
    setTimeout(() => {
        console.log(3, a)
    },300)
    setTimeout(() => {
        console.log(4, this.a)
    },400)
}
new A()


0
0

December_Hong

提问者

2020-12-09

为什么第二个输出的this指向的是window,第四个this指向的是A()

0
2
December_Hong
回复
双越
啊!老师我明白了!没有注意到是箭头函数!谢谢老师!
2020-12-09
共2条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程