OOjs/Inheritance
OOjs |
---|
Features |
See also |
OOjs builds on JavaScript's native prototypal inheritance model, adding mixins and inheritable static properties and methods.
Classes
[edit]A class can inherit methods and properties from a parent class. This is done by chaining the child class's prototype, making method and property lookups fall through to the parent's prototype.
First, call the parent's constructor within the child's constructor. This will initialize functionality provided by the parent class.
function Bar() {
// Parent constructor
Foo.call( this );
// [constructor code]
}
Second, use OO.inheritClass
to setup the prototype chain. This will also setup inheritance for inheritable static methods and properties.
OO.inheritClass( Bar, Foo );
When creating a base class, which other classes will inherit from but does not inherit from other classes, use the OO.initClass
method. This will add support for inheritable static methods and properties.
[code example]
Mixins
[edit]A class can mixin methods and properties from any number of other classes. This is done by copying methods and properties from the prototype of one class to another. Inheritable static methods and properties are also copied.
Classes are usually written specifically to be mixed into others. It is important to understand that only a class's own prototype properties will be copied when it is mixed into another class, so using inheritClass
for a mixin will cause inherited properties and methods to not be accessible.
First, call the mixin's constructor within the class's constructor. This will initialize functionality provided by the mixin class.
function Bar() {
// Mixin constructors
OO.EventEmitter.call( this );
// [constructor code]
}
Second, use OO.mixinClass
to copy the methods and properties to the class.
OO.mixinClass( Bar, OO.EventEmitter );
Static methods and properties
[edit]Some methods and properties are associated with the class rather than an instance of the class. If OO.inheritClass
, OO.mixinClass
, or OO.initClass
are called on a class, the constructor will have a static
property. This property is an object which has a prototype chain, allowing static methods and properties to be inheritable.
function Foo() {
// [constructor code]
}
OO.initClass( Foo );
Foo.static.baz = 'buz';
function Bar() {
// Parent constructor
Foo.call( this );
// Logs "buz"
console.log( this.constructor.static.baz );
}
OO.inheritClass( Bar, Foo );