Last active
December 15, 2016 23:50
-
-
Save allanesquina/8eefe932c6102da771fd083ce624bd72 to your computer and use it in GitHub Desktop.
A simple example of JavaScript prototypal inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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