如何在 oter 类中从类中调用方法?无法读取属性'test' JS


var test = function (){
this.text="hello word!!! ";

this.hello= function(){
alert(this.text);
}
}

我有这节课。。。我想用其他班级的这个班级来打招呼。所以我这样做:

class Alert{
test;
constructor(){
console.log("Starting class alert.")
this.test= new test();
}
say (){
test.hello()
}
}
main = new Alert();
main.say();

这让我想起了墨西哥最大的错误:

Uncaught TypeError: Cannot read property 'say' of undefined
at HTMLButtonElement.<anonymous>

所以我不知道如何解决,如果有人知道可以帮助。。。

不要忘记使用varletconst来声明变量。

此外,如果要在类内部调用方法,请使用this关键字。

var test = function (){
this.text="hello word!!! ";
this.hello= function(){
alert(this.text);
}
}
class Alert{
test;
constructor(){
console.log("Starting class alert.")
this.test= new test();
}
say (){
this.test.hello()
}
}
var main = new Alert();
main.say();

var test = function (){
this.text="hello word!!! ";
this.hello= function(){
alert(this.text);
}
}
class Alert{
test;
constructor(){
console.log("Starting class alert.")
this.test= new test();
}
say (){
this.test.hello()
}
}
var main = new Alert();
main.say();

最新更新