Search

4/08/2009

Javascript inheritance performance

KevLinDev - Tutorials - JavaScript


KevLinDev.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;

subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}

function Employee(first, last, id) {
// initialize properties here
}

KevLinDev.extend(Employee, Person);

We begin by creating a convenience function to setup our inheritance chain. We need the subClass.prototype property to be equivalent to baseClass.prototype. (Remember, when we call "new" that prototype property will be copied to the new instance's private prototype, thus hooking up its inheritance chain.) However, we can't allow both the subClass.prototype and the baseClass.prototype to point to the same prototype object. That would mean adding methods to one class would add it to the other. That's fine if we add to the base class, but the base class would also "inherit" methods we added to the subClass. We need a way disconnect the two prototypes while still allowing the subClass to refer to the baseClass. Once again, the prototype chain comes to the rescue.

Class-Based Inheritance in JavaScript
JavaScript OOP: encapsulation, durable objects, parasitic inheritance and the decorator pattern
Web Reflection: On JavaScript Inheritance Performance and Libraries Troubles
http://www.sitepoint.com/article/javascript-objects/
JavaScript Inheritance Performance « Broofa.com
Ajaxian » JavaScript Inheritance Performance

沒有留言: