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);