Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OLOO Pattern clarification

Tags:

javascript

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

like image 399
swent Avatar asked Oct 29 '15 21:10

swent


1 Answers

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:

  1. You create a Parent instance, copy from it, then throw it away.
  2. Any methods on Parent.prototype would not be inherited
  3. instanceof Parent will not be supported
  4. instanceof Child will not be supported

Object.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.

like image 158
jfriend00 Avatar answered Oct 15 '22 10:10

jfriend00