Last active
March 28, 2019 23:41
-
-
Save ilearnjavascript/b7aa340672ccede0257106ba05d7672e to your computer and use it in GitHub Desktop.
Prototypal Inheritance in ES5 and ES6 (Class)
This file contains hidden or 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
// ES5 - variant 1 | |
var es5_Person = function (firstname, lastname) { | |
this.firstname = firstname; | |
this.lastname = lastname; | |
this.greet = function () { | |
console.log('Hello I am ' + this.firstname + ' ' + this.lastname); | |
} | |
} | |
var es5_john = new es5_Person('John', 'Doe'); | |
es5_john.greet(); // outputs: Hello my name is John Doe | |
// ES5 - variant 2 | |
var es5_Person = function (firstname, lastname) { | |
this.firstname = firstname; | |
this.lastname = lastname; | |
} | |
es5_Person.prototype.greet = function () { | |
console.log('Hello I am ' + this.firstname + ' ' + this.lastname); | |
} | |
var es5_john = new es5_Person('John', 'Doe'); | |
es5_john.greet(); // outputs: Hello my name is John Doe | |
// ES6 Class | |
class es6_Person { | |
constructor(firstname, lastname) { | |
this.firstname = firstname; | |
this.lastname = lastname; | |
} | |
greet() { | |
console.log(`Hello I am ${this.firstname} ${this.lastname}`); | |
} | |
} | |
const es6_john = new es6_Person('John', 'Doe'); | |
es6_john.greet(); // outputs: Hello my name is John Doe | |
// Subclass | |
// ES5 | |
var es5_Soldier = function (firstname, lastname, weapon) { | |
// call person object with current this context | |
es5_Person.call(this, firstname, lastname); | |
this.weapon = weapon; | |
} | |
// The es5_Soldier.prototype creates a new object which has | |
// the es5_person.prototype as its __proto__ | |
es5_Soldier.prototype = Object.create(es5_Person.prototype); | |
// add new method to all soldier instances | |
es5_Soldier.prototype.shoot = function () { | |
console.log('Peng Peng with ' + this.weapon); | |
} | |
var jackTheSoldier = new es5_Soldier('Jack', 'The Soldier', 'AK47'); | |
jackTheSoldier.greet(); // outputs: Hello my name is Jack The Soldier | |
jackTheSoldier.shoot(); // outputs: Peng Peng with AK47 | |
// ES6 | |
// subclass | |
class es6_Soldier extends es6_Person { | |
constructor(firstname, lastname, weapon) { | |
super(firstname, lastname); | |
this.weapon = weapon; | |
} | |
shoot() { | |
console.log(`Peng Peng with ${this.weapon}`); | |
} | |
} | |
const janeTheSoldier = new es6_Soldier('Jane', 'Doe', 'Shotgun'); | |
janeTheSoldier.greet(); | |
janeTheSoldier.shoot(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment