【发布时间】:2016-11-07 21:27:18
【问题描述】:
我知道我可以用这段代码创建一个类:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
但是,我希望这个 Polygon 类驻留在名为 Model 的命名空间中,这样我就可以像这样实例化 Polygon 对象:
var myNewPolygon = new Model.Polygon(10, 50);
这可能吗?
我尝试了以下方法:
var Model = Model || {};
class Model.Polygon {
constructor() {
this.height = height;
this.width = width;
}
}
var myNewPolygon = new Model.Polygon(10, 50);
但这会导致第 2 行出现Uncaught SyntaxError: Unexpected token .。
我也试过了:
var Model = Model || {};
class Polygon {
constructor(height, width) {
this.height = height || 0;
this.width = width || 0;
}
}
Model.Polygon = new Polygon();
var myNewPolygon = new Model.Polygon(10, 50);
但这会导致第 9 行出现Uncaught TypeError: Model.Polygon is not a constructor。
【问题讨论】:
标签: javascript class namespaces