Javascript - 类路径有命名空间吗?

时间:2016-07-05 22:10:44

标签: javascript class namespaces

我知道我可以用这段代码创建一个类:

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

1 个答案:

答案 0 :(得分:3)

几乎就在那里。

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