我对在 JavaScript 中创建模块的方式有一些疑问。这是我发现的语法:
var Westeros;
(function (Westeros) {
(function (Structures) {
var Castle = (function () {
function Castle(name) {
this.name = name;
}
Castle.prototype.build = function () {
console.log("Castle " + this.name)
};
return Castle;
})();
Structures.Castle = Castle;
})(Westeros.Structures || (Westeros.Structures = {}));
var Structures = Westeros.Structures;
})(Westeros || (Westeros = {}));
var winterfell = new Westeros.Structures.Castle("Winterfell");
winterfell.build();
我拿了this code from Mastering Javascript Design Patterns .但是我试图找到你为什么需要这条线的答案:
var Structures = Westeros.Structures;
如果省略此行,代码将按预期工作。对此有什么解释吗?也许是为了“揭示”类(class)?
谢谢!
最佳答案
这段代码令人毛骨悚然。这是一个示例,它在没有所有无意义的闭包的情况下完成了一些事情:
function Castle(name) {
this.name = name;
}
Castle.prototype.build = function() {
console.log("Castle " + this.name)
};
var Westeros = {
Structures: {}
};
Westeros.Structures.Castle = Castle;
var winterfell = new Westeros.Structures.Castle("Winterfell");
winterfell.build();
在 ES5 中定义“类”时,您所要做的就是声明一个带有一些参数的函数,并在其中放置您想要的任何初始化代码。方法被添加到该函数的 .prototype
属性中,使用该类的新对象通过使用 new
关键字调用其构造函数来创建。
至于 var Structures = Westeros.Structures;
,它没有任何用处。如果您要保留原始代码示例,删除它不会有任何改变。事实上,它甚至不能被更多的代码进一步使用,因为它是在闭包内声明的,不能在该范围外访问。
关于Javascript 模块和设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409972/