01-11-2011

Javascript Prototype inheritance example

Many experienced programmers try to impose classical OO structures on JavaScript. Although it's possible JavaScript wasn't specifically designed for this. Using prototypes inheritance can be accomplished much simpler:

function Human(name) {
  this.name = name;
}
 
Human.prototype.greet = function() {
  console.log('Hello', this.name);
};
 
// Admin inherits from Human
 
function Admin(name) {
  this.name = name;
}
 
Admin.prototype = new Human;
 
var user = new Admin('alex');
 
// This method was defined on Human
user.greet();
 
 

Read more about this prototype and inhertance here: https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_constructor_prototype

Comments:

Your comment:

»

 

[x]