javascript - 从 Javascript 类中的静态方法引用成员函数的正确方法

标签 javascript class

我有一个类构造函数返回调用静态方法的结果的情况。

但是,在该静态方法中,我需要调用一个应该是成员函数的函数,但如果它是成员函数,则它不可用。

有什么好的方法吗?

这段代码应该有助于阐明:

class Program {
  constructor (paths) {
    this.inputs = {}
    this.program = Program.createProgram(paths)
    return this.program
  }

  static createProgram () {
      const return_program = {name: test}
      // async function executes
      this.modifyProgramName()  // This is an error because modifyProgram name is not static on this class
      return return_program
 }

 modifyProgramName() {
   // Execute a promise
   fetch('someresource').then(() => {
     this.program.name = 'newName'
   }, 500)
 }

这里的 modifyProgram 不应该是 static,因为“修改”程序的含义是它已经存在。

但是,当我想在本质上是构造函数的 createProgram 中调用 modifyProgram 时,我不能,因为 Program 类的实例还不存在。

有什么好的方法吗?

最佳答案

尝试将 this 传递给静态函数。像这样:

class Program {
  constructor (paths) {
    this.inputs = {}
    this.program = Program.createProgram(paths, this)
    return this
  }

  static createProgram (paths, program) {
      const return_program = {name: "test"}
      // async function executes
      program.modifyProgramName()  // This is an error because modifyProgram name is not static on this class
      return return_program
   }
  modifyProgramName() {
     setTimeout(() => {
       this.program.name = 'newName'
     }, 500)
  }
}

控制台的结果:

pgm = new Program(["/one"]);
Program {inputs: Object, program: Object}
pgm.program.name
"newName"

请注意,我将您的 setTimeout 更改为使用 => 格式,这样 this 将成为对象中的那个。

如果您不需要 createProgram 是静态的,那么这将起作用:

class Program {
  constructor (paths) {
    this.inputs = {}
    this.program = this.createProgram(paths)
    return this
  }

  createProgram (paths) {
      const return_program = {name: "test"}
      // async function executes
      this.modifyProgramName()  // This is an error because modifyProgram name is not static on this class
      return return_program
   }
  modifyProgramName() {
     setTimeout(() => {
       this.program.name = 'newName'
     }, 500)
  }
}

pgm = new Program(["/one"]);
Program {inputs: Object, program: Object}
pgm.program.name
"newName"

关于javascript - 从 Javascript 类中的静态方法引用成员函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750611/

相关文章:

delphi - Delphi Win32 中的类帮助器和字符串

javascript - 在 Electron 应用程序中模拟Ctrl + V

Javascript Jest 期望 0 等于 -0

javascript - Google 表格中的日期/时间未将正确的时间传输到 Google 日历中

ios - 如何制作 NSCountedSet 类的结构版本?

c++ - 如何在 C++ 中使用静态变量在不同类之间共享数组?

javascript - 将 "this"传递给在类中实例化的类

javascript - 数据表和 sScrollY、自动调整大小

javascript - 调用基类构造函数而无需手动提供参数

类类型作为 Scala 映射中的键