I'm not sure on the best approach to have object properties that are individual for each object in a OLOO inheritance chain.
Check this fiddle or consider the following code: http://jsfiddle.net/HB7LU/19413/
Parent = {
array: [],
add: function(element) {
this.array.push(element + this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
};
Child = Object.create(Parent, {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent);
foo.add('foo');
bar = Object.create(Child);
bar.add('bar');
In the fiddle a click on the foo or bar text will call the foo.add(...) or bar.add(...) function to add an element to the objects array, resulting in one extra <p>
tag in the output.
The result is not what I want. Both foo and bar share the same array. But its easy to understand what happens, if we look up the object inheritance we can see the following:
Ok then, what can I do go get around this? There were two options that came to my mind:
Option 1) http://jsfiddle.net/HB7LU/19419/
Parent = function() {
return {
array: [],
add: function(element) {
this.array.push(element + this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
};
};
Child = Object.create(Parent(), {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent());
foo.add('foo');
bar = Object.create(Child);
bar.add('bar');
This would create a new Parent object, creating all the functions of the Parent object each time a Parent object is created or a child "inherits" from a (new) Parent object. While this solves the problem I had, it seems like a bad idea to always recreate the same functions over and over again for each child type object.
Option 2) http://jsfiddle.net/HB7LU/19420/
Parent = Object.create({
add: function(element) {
this.array.push(element + this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
}, {
ctor: { value: function(someArgs) {
this.array = [];
// maybe use someArgs
return this;
}}
});
Child = Object.create(Parent, {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent).ctor();
foo.add('foo');
bar = Object.create(Child).ctor();
bar.add('bar');
This seems to also solve the problem but avoids the recreation of the Parent object and its functions. So is this the way to go? What if I had multiple children in the inheritance chain that also have private properties?
Something like this?
Child = Object.create(Parent, {
ctor: { value: function(someArgs) {
this.__proto__.ctor(someArgs);
this.otherPrivate = {};
// maybe use someArgs
return this;
}},
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
Children would be shadowing the parent ctor with their own function... but in their ctor function they could call the parents ctor to not break functionality.
Thoughts and advice is highly appreciated, thanks!