【发布时间】:2023-01-22 19:53:44
【问题描述】:
所以我试图理解 javascript 和内部函数中的 this 关键字。我有一个带有this关键字的内部函数,但它是returning "my hobby is undefined"。
我怎样才能让它返回"my hobby is programming"
这是我尝试过但没有用的方法:
function practice() {
function close() {
console.log(`my hobby is ${this.hobby}`)
}
return close()
}
let person = {
hobby: "programming"
}
let binding = practice.bind(person)
console.log(binding())
【问题讨论】:
-
每个
function都有自己的this,并且基于该函数的调用方式。因为close()在没有“上下文”的情况下被调用,所以close的this默认为默认全局对象(在浏览器中为window)。如果你想close使用来自周围范围的this值,那么你可以使它成为一个箭头函数,或者当你在practice内部调用它并通过practice的@时使用.call()987654338@。这主要在这里涵盖:How does the "this" keyword work, and when should it be used?
标签: javascript function closures this