Skip to content

Instantly share code, notes, and snippets.

@allanesquina
Last active December 15, 2016 23:50
Show Gist options
  • Save allanesquina/8eefe932c6102da771fd083ce624bd72 to your computer and use it in GitHub Desktop.
Save allanesquina/8eefe932c6102da771fd083ce624bd72 to your computer and use it in GitHub Desktop.
A simple example of JavaScript prototypal inheritance
// Person class
function Person(name) {
this.name = name;
}
// Adding getName method to its prototype
Person.prototype.getName = function () {
return this.name;
}
// Creating a new instance of Person
var person = new Person('Allan');
console.log(person.getName()); // Allan
// Develper class which inherit from Person
function Developer(name) {
// Calling Person constructor
Person.call(this, name);
}
// Setting Developer prototype from a new object based on Person prototype
Developer.prototype = Object.create(Person.prototype);
// Creating new instance of Developer
var dev = new Developer('JavaScript');
console.log(dev.getName()); // JavaScript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment