Prototypal inheritance example
by julienrf
HTML
<div id=result></div>
JavaScript
// Function wiring prototypes to achieve inheritance
function inherits(Parent, Child) {
function F() {}
F.prototype = Parent;
Child.prototype = new F();
}
// Base class
function Base(spec) {
this.name = spec.name; // Define the "name" property
}
// Child class
function Child(spec) {
Base.call(this, spec); // Call the base class constructor
}
inherits(Base, Child); // Wire prototypes
Child.prototype.sayHello = function () { // Define the "sayHello" method
return 'Hello, I\'m ' + this.name;
};
// Usage
var object = new Child({ name: 'a prototypal object' });
result.textContent = object.sayHello();