Skip to content

Instantly share code, notes, and snippets.

@teepark
Created February 26, 2010 23:15
Show Gist options
  • Save teepark/316301 to your computer and use it in GitHub Desktop.
Save teepark/316301 to your computer and use it in GitHub Desktop.
// subclassing AND instantiating
// (lazy lookups via prototype chain)
function clone(parent, extra) {
var child;
function klass() {};
klass.prototype = parent;
child = extra ? extend(new klass(), extra) : new klass();
// use parent.init in case `extra` contained an `init` override
if (parent.init && parent.init.call) parent.init.call(child);
return child;
};
// mixins/pseudo multiple inheritance
// (eager copying)
function extend(target, source) {
var key;
for (key in source) {
/* this check instead of hasOwnProperty because we do want inherited
attributes, just not if they are inherited from a common parent */
if (target[key] !== source[key])
target[key] = source[key];
}
return target;
};
var Animal = clone({}, {
'position': [0, 0],
// clones shouldn't share a position attribute with each other or the parent
'init': function() { this.position = this.position.slice(); },
'walk': function() { this.position[0] += 1; this.position[1] += 1;}
});
var Dog = clone(Animal, {
'bark': function() { return "woof!"; }
});
var clifford = clone(Dog, {
'size': 'big',
'color': 'red'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment