Can a Module Pattern object inherit from a Constructor Pattern object?
(I'm a bit new to javascript and the whole prototype/inheritance concept, so my apologies if this is a dumb question)
In my codebase, I've got a mishmash of Revealing-Module-Pattern type of objects, and then I've also got objects that use the Constructor-Pattern (where instances get newed-up).
I also have a block of code (written in the constructor-type-pattern) which provides EventEmitter functionality. Is it possible to use this code as a base class for both Constructor-Pattern objects and Revealing-Module-Pattern objects? Does trying to do this even make sense?
First, only "constructor-type-pattern" objects follow a traditional form of inheritance, where one class extends another and you make instances of objects.
"Revealing-module-pattern" is just a way of encapsulating data and exposing only parts of it, there isn't a concept of instances and classes when you use that pattern.
If you want to reuse code from such a "plain old object", you can use "prototypal inheritance", which simply means that your child object will point back to the parent object every time it is asked for a member it doesn't have.
In both case, you use Object.create
to create objects that have some other object for prototype, check out the examples at MDN.
Also note that ES2015 is out and makes classical OOP easier with nice native syntactic sugar in the form of class
and extends
.
下一篇: 模块模式对象是否可以从构造模式对象继承?