Ada*_*dam 5 javascript ecmascript-6
我有一些课程:
class Sample{
static createSelf() {
return new this.constructor(1, 2);
}
}
class AnotherClass extends Sample {
constructor(a, b) {
this.c = a+b;
}
}
ac = AnotherClass.createSelf();
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
这个具体的例子给了我SyntaxError: missing formal parameter,虽然在我的原始代码(500 行)中,当我有时new this.constructor(),我被SyntaxError: missing ] after element list指向第一行(形参错误也指向第一行)。我知道这是因为这一行,因为当我用普通的类名替换它时,它可以工作。没有关闭数组初始化。错误不可能意味着:
某处数组初始值设定项语法有错误。可能缺少右括号 ("]") 或逗号 (",")。
来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_bracket_after_list
更新原始代码:
class Participant {
constructor(origin, destination, number, startDate, endDate) {
...
}
static restore(save) {
const participant = new this.constructor(
new Marker(save.originLocation, this.getMarkerOptions(true, save.isDriver, save.number)).addTo(map),
new Marker(save.destinationLocation, this.getMarkerOptions(false, save.isDriver, save.number)).addTo(map),
save.number,
save.startDate,
save.endDate
);
return participant;
};
}
class Driver extends Participant {}
d = Driver.restore(saveObject);
Run Code Online (Sandbox Code Playgroud)
如果错误指向第一行,则语法错误位于您在此处发布的代码之前。
事实证明,此错误的原因是指this.constructor它将Function评估作为代码传递给它的参数之一。由于您没有将 JavaScript 代码传递给它,因此您会收到语法错误。
示例(打开浏览器的控制台):
new Function({});Run Code Online (Sandbox Code Playgroud)
但是,您在此处发布的代码也存在两个问题。
this静态方法内部
的值this取决于函数的调用方式。静态方法作为构造函数的方法被调用,因此this指的是构造函数。在您的示例中,AnotherClass.createSelf();,this指的是AnotherClass。故this.constructor指Function. 我不认为这就是你想要的。我猜你想要
class Sample{
static createSelf() {
return new this(1, 2);
}
}
Run Code Online (Sandbox Code Playgroud)
看起来您认为this会引用该类的一个实例,但它怎么可能呢?您还没有创建一个。
this构造函数内部
当一个类扩展另一个类时,您始终必须super()在访问之前在构造函数内部调用this:
class AnotherClass extends Sample {
constructor(a, b) {
super();
this.c = a+b;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2132 次 |
| 最近记录: |