我知道我可以使用以下代码创建一个类:
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
。
最佳答案
快到了。
var Model = Model || {};
Model.Polygon = class {
constructor(height, width) {
this.height = height || 0;
this.width = width || 0;
}
}
var myNewPolygon = new Model.Polygon(10, 50);
类可以是未命名的(又名“匿名”),就像函数一样,就像函数一样,unnamed classes can be assigned to variables ,如上 Model.Polygon = class { ... }
如果您需要类在类体内引用自身,那么您可以给它一个名称。请注意,类名在类主体之外不可用。
var Model = Model || {};
Model.Polygon = class Polygon {
constructor(height, width) {
this.height = height || 0;
this.width = width || 0;
}
equals(other){
// Returns true if other is also an instance of Polygon
// and height and width are the same.
return ( other instanceof Polygon ) &&
( other.height === this.height ) &&
( other.width === this.width );
}
}
var myNewPolygon1 = new Model.Polygon(10, 50);
var myNewPolygon2 = new Model.Polygon(10, 50);
myNewPolygon1.equals( myNewPolygon2 ); // returns true
myNewPolygon1.equals({ height: 10, width: 50 }); // returns false
var myNewPolygon3 = new Polygon(10, 50); // Uncaught ReferenceError: Polygon is not defined
关于Javascript - 类路径可以有命名空间吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38213653/