我有一个类如下:
const Module = {
Example: class {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new Module.Example(a);
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是有效的,但通过全局名称访问当前的类构造函数Module.Example是一种丑陋和容易破坏.
在PHP中,我会使用new self()或者new static()在这里引用定义静态方法的类.在Javascript中是否有类似这样的东西不依赖于全局范围?
cas*_*raf 18
你可以this在静态方法中使用.它将引用类本身而不是实例,因此您可以从那里实例化它.所以:
const Module = {
Example: class Example {
constructor(a) {
this.a = a;
}
static fromString(s) {
// parsing code
return new this(s);
}
copy() {
return new this.constructor(this.a);
}
}
}
const mod = Module.Example.fromString('my str');
console.log(mod) // => { "a": "my str"
console.log(mod.copy()) // => { "a": "my str" }
console.log('eq 1', mod === mod) // => true
console.log('eq 2', mod === mod.copy()) // => falseRun Code Online (Sandbox Code Playgroud)