OOPK

I am still involved, but recently I changed the field in which I want to work in web development. Therefore, programming is not new for me, but I have never looked twice in javascript.

I am trying to learn quickly, but I am confused about the different inheritance patterns used in javascript. I looked at the classic prototype chain where the .prototype task is set by the programmer (I think this is usually called the prototype). Then I read many blogs and articles about OLOO and its advantages regarding simplicity.

So, I tried a little coding of the sample and, exploring a good approach, came up with code that I can’t fit into either of these two categories.

I made a fiddle if I want to see: http://jsfiddle.net/HB7LU/19377/

For someone 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 I did here and what disadvantages I will use using this method. I know that this cannot be OLOO, because OLOO relies on a simple Object.create(...); to create new objects.

EDIT: violin link was broken, sorry

+8
javascript
source share
1 answer

What you do is like a mixin pattern. You create a new Parent object and then partially merge it into a Child object, which is a kind of idea to create a mixin.

Here are some links to mixins:

Fresh look at Javascript Mixins

Mixin Template

JavaScript Mixins: Beyond Simple Object ExtensionPosted

Here are some of the disadvantages of what you do:

  • You create an instance of Parent , copy it, and then discard it.
  • Any methods in Parent.prototype will not be inherited.
  • instanceof Parent not supported
  • instanceof Child not supported

Object.assign() only copies the listed native properties, so it does not copy the entire state of the Parent object, so it can be used only in this case, when you clearly know that the parent object does not have any of the things that will not be copied.

+6
source share

All Articles