最简单的 仅仅把对象附加到global命名空间
Westeros = {}
典型的用法是先检验此对象是否存在,存在就使用已经存在的而不是在设值如下:
Westeros = Westeros || {}
对象存在的话,设置我们的类到这个对象的属性上, 用 Castle 对象:
let Westeros = Westeros || {}
Westeros.Castle = function (name){this.name = name;}; //constructor
Westreros.Castle.prototype.Build = function(){console.log("Castle built :" + this.name;)};
如果我们要构建一个
超过单个级别的命名空间层次结构,这也很容易完成, 如本代码所示
let Westeros = Westeros || {};
Westeros.Structures = Westeros.Structures || {};
Westeros.Structures.Castle = function(name){ this.name = name}; //constructor
Westeros.Structures.Castle.prototype.Build = function(){console.log("Castle built: " + this.name)};
Westeros.Structures = Westeros.Structures || {};
Westeros.Structures.Castle = function(name){ this.name = name}; //constructor
Westeros.Structures.Castle.prototype.Build = function(){console.log("Castle built: " + this.name)};
这个类的实例:
let winterfell = new Westeros.Structures.Castle("Winterfell");
winterfell.Build();