在 try catch 块中调用类方法?

问题描述 投票:0回答:2

我遇到过这样的事情:

class Example {
  // ...

  async #privateMethod() {
    return true
  }

  static staticMethod() {
    try {
       // can't access #privateMethod
      this.#privateMethod()
    } catch (error) {
      console.log('error', error);
    }
  }
}

我想在静态方法中调用一个私有方法,但由于某些原因无法访问私有方法。请问我做错了什么?

javascript oop ecmascript-6 es6-class
2个回答
2
投票

那个私有方法是一个实例方法,这意味着你需要

this
成为Example
实例
来做
this.#privateMethod

运行静态方法时,您没有实例。相反,

this
指的是构造函数(“类”)。

这可能表明

#privateMethod
毕竟不应该是一个实例方法,因为它可以在没有实例方法的情况下完成它的工作。

如果是这种情况,那么只需将该私有方法也设为静态即可:

class Example {
  // ...

  static async #privateMethod() {
    console.log("running private static method");
    return true;
  }

  static staticMethod() {
    try {
      this.#privateMethod()
    } catch (error) {
      console.log('error', error);
    }
  }
}

Example.staticMethod();


0
投票

在静态方法中没有这样的东西。这是用

创建的类的实例
myClassInstance = new Classname(); 

然后调用方法

MyClassInstance.myMethod();

在此方法中,您可以将其用作指向 myClassInstance 的指针。

在没有这样的实例的情况下调用静态方法,所以你没有 this,所以你不能调用非静态方法。

© www.soinside.com 2019 - 2024. All rights reserved.