gpt4 book ai didi

javascript - 扩展子函数不能使用 'this' ,关键字未定义

转载 作者:行者123 更新时间:2023-12-03 04:16:24 26 4
gpt4 key购买 nike

我的 createCon 函数使用它来设置该对象的 con。我发现这是未定义的。错误:无法设置未定义的“con”属性。能够从对象函数引用 this 最好的是什么?

class parent {
constructor(stringA, stringB){
this.config = {};
this.con = {};
}
}

class child extends parent {
constructor(stringA, stringB) {
super(stringA,stringB)
this.config = {
full : stringA+stringB
}
}

createConn(){
var con = con(this.config.full);
con.connect(function(err){
if(!err) this.con = con;
})
}
}

最佳答案

您正在函数内使用this关键字。 this 与其他 OOP 语言不同,它指的是“上下文”,它可以根据函数的执行而改变。

您想要使用箭头函数,它将在词法上绑定(bind)(即保留)定义箭头函数的上下文的 this

createConn(){
var con = con(this.config.full);
con.connect((err) => {
if(!err) this.con = con;
})
}

关于javascript - 扩展子函数不能使用 'this' ,关键字未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44122756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com