【问题标题】:Javascript - can class paths have namespaces?Javascript - 类路径可以有命名空间吗?
【发布时间】: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


    【解决方案1】:

    差不多了。

    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
    

    【讨论】:

    • 看起来我可以像您的第一个示例一样使用匿名类。然后,如果我需要引用类本身,我可以使用完整的命名空间路径。 (this instanceof Model.Polygon) 将在第一个示例中返回 true,即使 Model.Polygon 指向匿名类。
    • 是的。但是缩小器无法缩小 Model.Polygon(假设您导出模型命名空间),但可以缩小 Polygon(因为名称是本地范围的)。根据您引用该名称的频率(以及是否缩小文件),它可能会在下载时间和整体网页响应能力方面产生几个字节的差异。
    • (注意:显然对 ECMA 6 的 uglifier/minifier 支持仍然是 not universal
    猜你喜欢
    • 2016-03-02
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2017-04-29
    • 1970-01-01
    • 2014-09-15
    • 2010-10-03
    相关资源
    最近更新 更多