我知道我可以用下面的代码创建一个类:
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);
类可以像函数一样被命名(又名"匿名"),也可以像函数一样,未命名的类可以被赋值给变量,就像上面的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