2 ms·
To cut the story short, there is basically a single way to do "proper" inheritance in javascript, which is Crockford's prototypal inheritance [1]. There are a d
by ricardobeat 14y ago
To cut the story short, there is basically a single way to do "proper" inheritance in javascript, which is Crockford's prototypal inheritance [1]. There are a dozen variations on it, here is one:
function inherits (child, parent) {
extend(child, parent)
function Ctor () { this.constructor = child }
Ctor.prototype = parent.prototype
child.prototype = new Ctor()
child.__super__ = parent.prototype
return child
}
function Animal ...
Animal.prototype.x = ...
function Cat ...
inherits(Cat, Animal)
See Backbone's implementation [2] for another example. This eventually morphed into the standard `Object.create` method [3], supported in IE9+.
[1] http://javascript.crockford.com/prototypal.html http://javascript.crockford.com/prototypal.html
[2] http://backbonejs.org/docs/backbone.html#section-186 http://backbonejs.org/docs/backbone.html#section-186
[3] https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...