Prototypal Inheritance in JavaScript

Prototypal Inheritance – How To Node – NodeJS

A nice article on prototypal inheritance using some ES5 features (available in modern browsers and Node.js). Here’s an example of the code he comes up with:

Object.defineProperty(Object.prototype, "spawn", {value: function (props) {
  var defs = {}, key;
  for (key in props) {
    if (props.hasOwnProperty(key)) {
      defs[key] = {value: props[key], enumerable: true};
    }
  }
  return Object.create(this, defs);
}});

//animals2
var Animal = {
  eyes: 2,
  legs: 4,
  name: "Animal",
  toString: function () {
    return this.name + " with " + this.eyes + " eyes and " + this.legs + " legs."
  }
}
var Dog = Animal.spawn({
  name: "Dog"
});
var Insect = Animal.spawn({
  name: "Insect",
  legs: 6
});
var fred = Dog.spawn({});
var pete = Insect.spawn({});
sys.puts(fred);
sys.puts(pete);

Comment

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>