我有一个类构造函数返回调用静态方法的结果的情况。
但是,在该静态方法中,我需要调用一个应该是成员函数的函数,但如果它是成员函数,则它不可用。
有什么好的方法吗?
这段代码应该有助于阐明:
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/