Created
May 9, 2013 11:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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