I'm still studying but lately changed the field I want to work in to web development. So programming is nothing new to me but I never really looked twice at javascript.
I'm trying to learn fast but I got confused about the different inheritance patterns used in javascript. I looked up on the classical prototype chain where the .prototype reference is set by the programmer (I think this is commonly refered to as prototype pattern). Then I was reading lots of blogs and articles about OLOO and its advantages regarding simplicity.
So I tried coding a little sample myself and while researching for a good approach I came up with a snipped of code that I can't really put into any of those two categories.
I made a fiddle if one wants to have a look: http://jsfiddle.net/HB7LU/19377/
For anyone else, this is basically my code:
function Parent() {
return {
array: [],
add: function(element) {
this.array.push(element + this.array.length.toString());
},
getAll: function() {
return this.array;
},
};
};
function Child() {
return Object.assign(Parent(), {
removeAllButOne: function() {
this.array.splice(1);
}
});
};
foo = Parent();
foo.add('foo');
bar = Child();
bar.add('bar');
foo.add('foo');
bar.add('bar');
bar.removeAllButOne();
Hopefully someone can clarify what it is I did here and what drawbacks I'll face using this method. I know it can't be OLOO because OLOO relies on a simple Object.create(...);
to create new objects.
EDIT: Link to fiddle was broken, sorry
What you are doing is somewhat like a mixin pattern. You're creating a new Parent
object, then partially merging it into the Child
object which is kind of the idea behind a mixin.
Here are some references on mixins:
A Fresh Look at Javascript Mixins
The Mixin Pattern
JavaScript Mixins: Beyond Simple Object ExtensionPosted
Here are some disadvantages of what you're doing:
Parent
instance, copy from it, then throw it away.Parent.prototype
would not be inheritedinstanceof Parent
will not be supportedinstanceof Child
will not be supportedObject.assign()
only copies enumerable, own properties so it does not copy the entire state of a Parent
object, thus it can only be used in this circumstance when you explicitly know the parent object doesn't have any of the things that will not be copied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With