Javascript Inheritance

Posted on November 1st, 2011, by Cristian in Javascript & jQuery

JavaScript is a bit confusing for developers coming from Java or C++, as it’s dynamic and does not provide a class implementation, although the keyword class is a reserved keyword and cannot be used as either a variable name or a property. JavaScript inheritance uses just three key ideas:

  • An object’s methods (like all properties) are found by walking up the object’s prototype chain;
  • The entries in the prototype chain are references to ordinary objects;
  • Object.create() or the new operator creates objects with a longer prototype chain.

Here is a simple Javascript inheritance example to learn from:

var user;

function Person (name) {
  this.name = name;
}

Person.prototype.hello = function() {
  console.log('Hello', this.name);
};

// Student inherits from Person

function Student (name) {
  this.name = name;
}

Student.prototype = new Person;

user = new Student('George');

// This method was defined on Person

user.hello();

If you are interested to read more about prototype chains check here: Inheritance and the prototype chain.

Leave a comment

Advertise / Sponsors

Comments RSS Feed

Recent Comments

  • yuci: ok, i solved the problem, but i will search for a better one. i just noticed, hidden div doesnt show itself...
  • yuci: hey, yeah i downloaded well, and i edited a lot this application, and i can say that, it is a wonderful app....
  • Cristian: No, it’s working as I tested.
  • yuci: is link dead, or just some temporary problem? i cant download zip files.
  • Fredrik: I can’t get this to work. It seems to fail at $order->setShippingAmount( $shipping_amount +...