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

标签 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

最佳答案

快到了。

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/

相关文章:

python - 创建一个具有对象之间链接的类似迷宫的游戏

apache-flex - halo 和 mx 命名空间的区别

c++ - std::cout 的简约重新实现

javascript - Firefox 中的动态创建内容 iframe 问题

java - 如何从子类修改父类(super class)变量?

php - 如何在 PHP 类中使用 "hide"私有(private)变量

xml - XSD 架构 - 命名空间

javascript - 在 foreach 循环中获取多个链接

Javascript,按顺序执行脚本代码插入dom树

javascript - 如何使用 javascript 和 html 显示特定时区的内容