我对使用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();
我从“掌握Javascript设计模式”中获取了此代码。但是,我试图找到一个答案,为什么您需要此行:
var Structures = Westeros.Structures;
如果省略此行,代码将按预期工作。有什么解释吗?也许要“揭露”这堂课?
谢谢!
此代码令人恐惧。这是一个示例,它在没有所有无意义的闭包的情况下确实做了一些事情:
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;
,它毫无用处。如果要保留原始代码示例,则删除它不会有任何改变。实际上,它甚至不能被更多的代码使用,因为它是在闭包内部声明的,并且不能在该范围之外进行访问。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句