Some programmers advise against using pseudo classical inheritance in Javascript, but advise using duck-typing and giving each object a set of capabilities.
Is there
So you have these two functions:
function make ( props ) {
var obj = Object.create( {} );
Object.keys( props ).forEach(function ( key ) {
obj[ key ] = props[ key ];
});
return obj;
};
function addMethods ( obj, methods ) {
var proto = Object.getPrototypeOf( obj );
Object.keys( methods ).forEach(function ( key ) {
proto[ key ] = methods[ key ];
});
}
Usage:
var simba = make({
name: "Simba",
type: "lion"
});
addMethods( simba, {
swim: function () {},
run: function () {}
});
addMethods( simba, {
hunt: function () {},
kill: function () {}
});
Live demo: http://jsfiddle.net/UETVc/