Skip to content

Instantly share code, notes, and snippets.

@Skateside
Created May 9, 2013 11:33
Show Gist options
  • Save Skateside/5546955 to your computer and use it in GitHub Desktop.
Save Skateside/5546955 to your computer and use it in GitHub Desktop.
Playing around with simplifying inheritance in JavaScript. Not sure if this ill ever work, but worth playing with, I think.
function forin(obj, fn) {
var prop = '';
for (prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
fn.call(null, obj[prop], prop, obj);
}
}
}
function enhance(source, extra) {
var created = Object.create(source),
constructor = function () {};
forin(extra, function (value, key) {
if (key in created) {
created['$parent_' + key] = created[key];
}
created[key] = value;
});
constructor.prototype = created;
return constructor;
}
function callParent(method, context, args) {
var proto = Object.getPrototypeOf(context),
superMethod = proto['$parent_' + method];
return method.apply(context, args);
}
function Foo() {
this.init();
}
Foo.prototype = {
name: 'Foo',
init: function () {
console.log('Foo.init');
}
};
var Bar = enhance(Foo, {
name: 'Bar',
init: function () {
console.log('Bar.init');
callParent('init', this);
}
});
var Baz = enhance(Bar, {
name: 'Baz',
init: function () {
console.log('Baz.init');
callParent('init', this);
}
});
var foo = new Foo(),
bar = new Bar(),
baz = new Baz();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment