【发布时间】:2019-08-23 13:14:15
【问题描述】:
我正在试验 this 和箭头函数。 在 setTimeout 中箭头函数的词法范围遇到了一些问题。
makeSound 方法将 this 作为 dog 对象返回。由于箭头函数在 setTimeout 方法中,为什么它不占用全局对象的范围?有趣的是,whatIsThis 方法返回的是 Timeout 对象,而不是全局对象。我对此也感到困惑。
const dog = {
name: 'fluffy',
type: 'dog',
sound: 'woof!',
makeSound: function() {
setTimeout(() => {
console.log("makeSound", this)
}, 1000)
},
whatIsThis: function() {
setTimeout(function() {
console.log("whatisthis", this)
}, 1000)
}
}
dog.makeSound() // returns dog obj
dog.whatIsThis() // returns Timeout obj
setTimeout(() => {
console.log("global", this)
}, 1000) // returns global obj
【问题讨论】:
-
你确定 dog.whatIsThis() 记录了 Timeout 对象。对我来说,它记录了窗口对象,这很有意义,因为您声明了一个由 setTimeout 调用的新词法范围。箭头函数从外部词法范围获取它的 this(在你的例子中是 makeSound,它等于 dog)。
标签: javascript ecmascript-6 this settimeout arrow-functions