Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript类中使用静态方法及其值_Javascript_Class_Oop - Fatal编程技术网

在Javascript类中使用静态方法及其值

在Javascript类中使用静态方法及其值,javascript,class,oop,Javascript,Class,Oop,我有一个Javascript“GLProgram”类,负责从两个字符串编译WebGL程序 编译程序不是对程序本身调用的方法,因此它看起来应该是静态的 但是,它会多次调用未全局定义的WebGL对象 为了不必将这个GL对象传递给每个函数,我通常创建一次对象,然后将其存储在类中 该类如下所示: class GLProgram { constructor () { this.gl = gl } static makeProgram () { //

我有一个Javascript“
GLProgram
”类,负责从两个字符串编译WebGL程序

编译程序不是对程序本身调用的方法,因此它看起来应该是静态的

但是,它会多次调用未全局定义的
WebGL
对象

为了不必将这个
GL
对象传递给每个函数,我通常创建一次对象,然后将其存储在类中

该类如下所示:

class GLProgram {
     constructor () {
       this.gl = gl  
    }
    static makeProgram () {
       // Do stuff with this.gl
    }
}
问题是如果
makeProgram
是静态的,
this.gl
没有定义

对于我来说,唯一的解决方案是使其成为一个非静态函数(这在概念上是错误的),还是永远传递对调用
gl
对象的
gl
函数的引用

下面是我想做的一个更完整的例子:

class GLProgram {
     constructor (vert, frag) {
       this.gl = gl
       GLProgram.makeProgram(vert, frag)
    }
    static makeProgram (shader1, shader2) {
       // Do stuff with this.gl
    }
}

   const myProgram = GLProgram('myshader', 'myshader2')
   // But this could also be
   const myProgram2 = GLProgram.makeProgram('myshader', 'myshader2')
   // But this doesn't work because GLProgram can not access this.gl

我知道,
这个
在Javascript的静态函数中是未定义的,所以这是否意味着我必须传入一个引用到其他地方定义的变量?

“从概念上讲,这应该是一个静态方法,因为它与此程序的实例无关。”这是不正确的,因为编译后的程序需要与实例关联。问题已解决。静态方法->静态属性-或者可能是具有模块范围变量的模块,而不是class@Ryan为什么编译后的程序需要与实例关联?@Ryan我认为“与此程序的实例无关”OP指的是
类GLProgram
,不是返回的
WebGLProgram
makeProgram
函数可以(应该?)很好地是静态的,就像静态工厂方法一样。Startec,您能给出一个完整的示例,说明如何使用
GLProgram