如何通过模块模式创建子模块
我正在阅读有关 JavaScript 模块模式的内容。我的问题是如何用它创建子模块,即如何从它继承,假设我有这个类,
var MODULE = (function () {
my = function(){
this.params = ""
},
privateVariable = 1;
my.prototype.moduleMethod = function () {
console.log("mod");
};
return my;
}());
如何使用从父级继承的属性创建它的子类?我怎样才能对模块模式做同样的事情?
I was reading about JavaScript Module pattern. My Question is how do I make submodules with it, i.e how can I inherit from it, say I have this class
var MODULE = (function () {
my = function(){
this.params = ""
},
privateVariable = 1;
my.prototype.moduleMethod = function () {
console.log("mod");
};
return my;
}());
How do I make a child class of it with properties inherited from parent? How can I do the same with module pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模块模式不是类模式。你不能简单地假装你现在有 JavaScript 类。至于继承,如果你确实需要继承东西,你应该通过构造函数创建一个对象并使用原型继承,尽管有时执行速度较慢。
至于创建子模块很简单
现在,对于经典意义上的子类化,您可以在具有原型的对象上进行模拟,就像 Douglas Crockford 所做的那样 http://www.crockford.com/javascript/inheritance.html
要使用模块进行模拟,您可以尝试在原始模块内创建 seal/unseal 函数并在子模块中使用它们。您可以在此处查看 http://www.pallavlaskar.com/javascript-module-pattern-in-details /
用于
克隆和继承
或
跨文件私有状态
The module pattern is not a class pattern. You cannot simply pretend you now have classes in JavaScript. As for inheritance, if you really need to inherit stuff, you should make an object via constructor function and use prototypal inheritance, although it's sometimes slower to execute.
As for creating a submodule it's simple
Now, as for subclassing in the classical sense, you can simulate it on objects with prototypes, like Douglas Crockford does http://www.crockford.com/javascript/inheritance.html
For simulating it with modules, you can try by creating a seal/unseal functions inside the original module and use them in your submodules. You can check here http://www.pallavlaskar.com/javascript-module-pattern-in-details/
for the
Cloning and Inheritance
or the
Cross-File Private State
如果my没有用var声明,那么当函数执行时它就会变成全局的。另外,按照惯例,构造函数的名称以大写字母开头,因此:
但您也可以只声明该函数并完成它:
。
如果您只是实现原型继承,为什么还要使用模块模式呢?
模块模式并不是为了继承,而是为了创建功能“模块”并在某种程度上模拟公共、特权和私有成员。
If my is not declared with var, it becomes global when the function executes. Also, by convention constructors have names starting with a capital letter, so:
but you may as well just declare the function and be done with it:
.
If you are just implementing prototype inheritance, why use the module pattern at all?
The module pattern is not meant for inheritance but to create "modules" of functionality and emulate public, priveleged and private members to some extent.