JavaScript: Prototypal Inheritance with Object.create

Overview Prototypal Inheritance

  • Define Constructor functions and Prototypes names [ CatObj, Mammal ] in UpperCamelCase Notation
  • Define all other Objects working like Object Instances in Java [ felicitas, fini ] with LoverCamelCase Notation
  • Prototypal Inheritance means we walk down the Prototype Chain until a certain Method or Property was found
  • Prototypes do not lend their properties to the next object in the chain, they rather lend it to the first object in the chain

Following the Function Chain

inherit2inherit1
Object Chain                                        Function Chain
 
Object Chain Details  
   - mammalObj inherits type Property from String Literals Object Mammel
   - mammalObj also inherits same functions  from Object.protype  like hasOwnProptery()
Function Chain Details 
   - mammlObj inherits from Object.prototype functions like bind(), call() and apply()  

JavaScript Code: 
var Mammal = {
    type: 'Mammal',
    getDetails: function () {
        return(this.type );
    }
};

function runObjectTest9() {
    logMessage('--- Prototypal Inheritance via Object.create [ for details check JavaScript console ] ---');
    var mammelObj  = Object.create(Mammal);
    logMessage("mammelObj.getDetails():: " + mammelObj.getDetails());
    logMessage("mammelObj.type :: " + mammelObj.type);
    try {
        logMessage("mammelObj.getAge():: " + mammelObj.getAge());
    }   catch (e) {
        logMessage("FATAL ERROR:: Catching Exception running mammelObj.getAge() :: " + e);
    }
    logMessage("mammelObj.age :: " + mammelObj.age);
.....

Output
10:54:08:439 mammelObj.getDetails():: Mammal
10:54:08:439 mammelObj.type :: Mammal
10:54:08:440 FATAL ERROR:: Catching Exception running mammelObj.getAge() ::
                TypeError: mammelObj.getAge is not a function
10:54:08:440 mammelObj.age :: undefined


  • Object.create can use Object Literals to create new Objects
  • For

 

Leave a Reply

Your email address will not be published. Required fields are marked *