提问人:ToYlet 提问时间:1/22/2023 最后编辑:Nick ParsonsToYlet 更新时间:1/22/2023 访问量:50
内部函数中的此关键字不起作用 (Javascript) [重复]
This keyword in an Inner Function not working (Javascript) [duplicate]
问:
所以我正在尝试理解 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())
答:
0赞
bee
1/22/2023
#1
因此,您需要将数据绑定到函数内部的内部函数,并将它们绑定到外部函数。见下文:
function practice() {
function close() {
console.log(`my hobby is ${this.hobby}`)
}
let binding2 = close.bind(this)
return binding2()
}
let person = {
hobby: "programming"
}
let binding = practice.bind(person)
binding()
评论
2赞
Nick Parsons
1/22/2023
你在这里指的是什么循环?您可以直接执行,而无需 if 语句。但是,如果您这样做,然后直接拨打电话,您不妨使用代替:)let bidnging2 = close.bind(this);
binding2()
binding2.call(this)
0赞
bee
1/22/2023
你是对的,出于某种原因,当我测试代码时,在我发布它之前,我得到了一个循环,所以添加了一个以避免它哈哈
1赞
Nick Parsons
1/22/2023
也许您可以编辑您的答案以修复答案的那部分:)
1赞
Lucasbk38
1/22/2023
#2
你的内部函数应该是一个箭头函数,因为一个普通的函数会覆盖上下文:this
function practice() {
const close = () => {
return `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
.call()
practice
practice
this