Tuesday, April 8, 2014

Javascript prototypal inheritance with Object.create


An advantage that can turns out in disadvantage is that Javascript is a very expressive language. You can do something in very different ways. In this case I'll show a way to model inheritance using Object.create (ECMAScript 5).

In the following example, two objects are created: parent and child. These both objects are like "classes" in lenguajes with classical inheritance as Java. From those objects, I create two instances using Object.create: Pepe (the parent) and Pablo (the child). In this case, Pablo prototypically inherits from Pepe.


// In case of using IE 
if (typeof console === 'undefined') {
  console = {
  log: function(text) {
  alert(text);
  }
  }
}
    
// In case of using IE<10
if(typeof Object.create !== 'function') { 
  Object.create = function (o) { 
    function F() {}; 
    F.prototype = o; 
    return new F(); 
  }; 
}
    
// Helper to add properties to an object
function extend(obj, props) { 
  for(prop in props) { 
    if(props.hasOwnProperty(prop)) { 
      obj[prop] = props[prop]; 
    } 
  } 
}
    
    // Parent object
var parent = {
talk: function() {
console.log("I'm "+this.name);
},
work: function() {
console.log("I'm going to work");
},
init: function(name) {
this.name=name;
return this;
},
create: function(name) {
return Object.create(this).init(name);
}
};

// Child object
var child = Object.create(parent)
extend(child, {
work : function() {
    console.log("I can't work, I'm a child!");
}
});

// Parent instance
var pepe = parent.create("Pepe");

// Child instance
var pablo = child.create("Pablo");

pepe.talk(); // I'm Pepe
pepe.work(); // I'm going to work

pablo.talk(); // I'm Pablo
pablo.work(); // I can't work, I'm a child!


No comments:

Post a Comment