Javascript Object Oriented Design - Javascript object inheritance








To add inheritance between objects, specify what object should be the new object's [[Prototype]].

Object literals have Object.prototype set as their [[Prototype]] implicitly.

We can explicitly specify [[Prototype]] with the Object.create() method.

The Object.create() method accepts two arguments.

The first argument is the object to use for [[Prototype]] in the new object.

The optional second argument is an object of property descriptors.

Example

The following code shows how to create inheritance between objects.


var book1 = { 
    name : "Javascript", 
    writeLine : function() { //from w w  w  . j a  va2s . c  om
        console.log(this.name); 
    } 
}; 

var book2 = Object.create(book1, { 
    name : { 
        configurable : true, 
        enumerable : true, 
        value : "CSS", 
        writable : true 
    } 
}); 

book1.writeLine();          // outputs "Javascript" 
book2.writeLine();          // outputs "CSS" 

console.log(book1.hasOwnProperty("writeLine"));     // true 
console.log(book1.isPrototypeOf(book2));        // true 
console.log(book2.hasOwnProperty("writeLine"));     // false 

The code above generates the following result.





Note

To access the supertype method, we can directly access the method on the supertype's prototype and use either call() or apply() to execute the method on the subtype object.


function Rectangle(length, width) { 
    this.length = length; /*from   w w  w .ja v a2 s .  com*/
    this.width = width; 
} 

Rectangle.prototype.getArea = function() { 
    return this.length * this.width; 
}; 

Rectangle.prototype.toString = function() { 
    return "[Rectangle " + this.length + "x" + this.height + "]"; 
}; 

// inherits from Rectangle 
function Square(size) { 
    Rectangle.call(this, size, size); 
} 

Square.prototype = Object.create(Rectangle.prototype, { 
                        constructor : { 
                            configurable : true, 
                            enumerable : true, 
                            value : Square, 
                            writable : true 
                        } 
                    }); 

// call the supertype method 
Square.prototype.toString = function() {  
    var text = Rectangle.prototype.toString.call(this); 
    return text.replace("Rectangle", "Square"); 
};