【问题标题】:How to call a method from a class in oter class? Cannot read property 'test' JS如何从其他类中的类调用方法?无法读取属性“测试”JS
【发布时间】:2020-11-22 14:53:53
【问题描述】:
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();

这让我看到了 mext 错误:

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

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

【问题讨论】:

  • 请同时添加产生错误的 HTML。另外,test.hello() 应该是 this.test.hello()
  • 还有javascript !== java
  • @adiga 是的,我做到了,但什么也没...
  • 除非这个问题同时包含java和javascript,否则请去掉不正确的标签。 Java 和 Javascript 是非常不同的语言。
  • this.test 是问题之一。您没有提供HTMLButtonElement 以及错误中提到的say 的调用方式。

标签: javascript java jquery


【解决方案1】:

不要忘记使用 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();

【讨论】:

  • 我做到了,什么也没做
猜你喜欢
  • 2020-07-29
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多