[英]how can I call a method only one time in a class? (first time when add "new")
我有很多方法的长代码,但是由于我在 stackoverflow 上,我将在这里添加一个简单的最小示例(不是最终的,但我希望向您展示错误):
我有这样的代码:
class MyClass { constructor() { this.myMethod(); } myMethod() { console.log("hello world;") } } new MyClass();
这段代码没问题。
该方法运行一次。
但如果我调用它超过 2 次,它将再次运行该方法。
/* other code */
new MyClass();
new MyClass();
new MyClass();
new MyClass();
new MyClass();
// wrong output:
hello world
hello world
hello world
...
// desired output (only one time)
hello world
如果您对为什么运行一次感兴趣。 这是因为我希望 class 首先创建一些 Ui 元素,然后获取生成的 ui 并使用构造函数中的给定参数更改内容
检查此文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
有一个关键字用于执行此操作的类,称为static
class MyClass { // no () just static and { your code } static { console.log("called once"); } myOtherMethod() { console.log("run when I want or every time") } } /* other code */ new MyClass(); new MyClass(); new MyClass(); new MyClass(); new MyClass();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.