Prototype inheritance and extension of existing objects
var Editor = {};
Editor.Basic = function(obj) {
this.config ={
value: obj
}
};
Editor.Basic.prototype = {
getValue: function() {
return this.config.value;
}
};
Editor.Advanced = function(obj) {
Editor.Basic.call(this, obj);
};
Editor.Advanced.prototype = {
config: {
notValue: !this.config.value
}
};
var extendByPrototype = function(obj1, obj2) {
for (var key in obj2.prototype) {
if (obj2.prototype.hasOwnProperty(key) && obj1.prototype[key] === undefined)
obj1.prototype[key] = obj2.prototype[key];
}
};
extendByPrototype(Editor.Advanced, Editor.Basic);
Editor.Advanced.prototype
Is there anyway to extend existing objects (recursively of course) instead of overriding them? (As seen from extendByPrototype
)
I know I would check obj1.prototype[key] !== undefined
, but I'm not sure what I need to do to extend existing keys in a generic way without moving config
from Editor.Advanced.prototype
to the constructor and using a push
function.
source to share
The correct way to extend an object in JavaScript is using Object.create(prototype)
. Objects created this way will inherit correctly. To get a prototype of any object, you will use Object.getPrototypeOf(object)
.
Object.create(prototype)
is new in JavaScript 1.8.5. If you are looking for backward compatibility you will have to use the non-standard way
function extend(child, supertype) {
child.prototype.__proto__ = supertype.prototype;
}
extend(Animal, Lifeform);
extend(Plant, Lifeform);
var anOnion = new Plant();
After that, you can get the prototype object with ...
object.contructor.__proto__
More on __proto__
here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/proto
source to share