2013-06-04

Best Practice of JavaScript Inheritence

Views: 5477 | Add Comments

Unlike other OO languages such as Java, JavaScript have no class grammar, the most similar concept to class is function. These codes below shows how to define a JavaScript class:

function Base(arg){
    var self = this;
    self.base = 1;
    self.name = 'base';
}

But how to inherits from other clsss? You need to use prototype.

function Child(arg){
    var self = this;
    self.name = 'child';
}

// Magic happens here!
Child.prototype = new Base();
Child.prototype.constructor = Child;

You can now use Child as usual:

var child = new Child();
alert(child.base + ', ' + child.name); // 1, child

You may want to wrap up the inheritence operation in one function:

function class_extend(child, base){
    child.prototype = new base();
    child.prototype.constructor = child;
}
class_extend(Child, Base);
Posted by ideawu at 2013-06-04 11:10:23

Leave a Comment