Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save westc/7c8513f95c61220a330e to your computer and use it in GitHub Desktop.

Select an option

Save westc/7c8513f95c61220a330e to your computer and use it in GitHub Desktop.
Example of simple prototypal inheritance before ES5.
// Define a simple Being prototype with isLiving(), die(), and _living starting
// off as true.
function Being() {}
Being.prototype._living = true;
Being.prototype.isLiving = function() { return this._living; };
Being.prototype.die = function() { this._living = false; };
// Define a simple Person prototype which is constructed with a gender.
function Person(gender) { this._gender = gender; }
// Make the Person prototype inherit from the Being prototype.
Person.prototype = new Being();
// Add a getter for gender only to the Person prototype.
Person.prototype.getGender = function() { return this._gender; }
// Test out a being.
var being1 = new Being();
console.log('Does being1 start off living?', being1.isLiving());
being1.die();
console.log('After executing being1.die() is being1 still living?', being1.isLiving());
console.log('Does being1 have a getGender function?', 'function' == typeof being1.getGender);
console.log('Is being1 an instance of Being?', being1 instanceof Being);
// Test out a person.
var person1 = new Person('Male');
console.log('Does person1 start off living?', person1.isLiving());
person1.die();
console.log('After executing person1.die() is person1 still living?', person1.isLiving());
console.log('Does person1 have a getGender function?', 'function' == typeof person1.getGender);
console.log("What is person1's gender?", person1.getGender());
console.log('Is person1 an instance of Being?', person1 instanceof Being);
console.log('Is person1 an instance of Person?', person1 instanceof Person);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment