Last active
April 26, 2023 16:16
-
-
Save drenther/e2e3d95930b2ed3d3560ce0985fd3421 to your computer and use it in GitHub Desktop.
Creational Pattern - Constructor
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
// traditional Function-based syntax | |
function Hero(name, specialAbility) { | |
// setting property values | |
this.name = name; | |
this.specialAbility = specialAbility; | |
// declaring a method on the object | |
this.getDetails = function() { | |
return this.name + ' can ' + this.specialAbility; | |
}; | |
} | |
// ES6 Class syntax | |
class Hero { | |
constructor(name, specialAbility) { | |
// setting property values | |
this._name = name; | |
this._specialAbility = specialAbility; | |
// declaring a method on the object | |
this.getDetails = function() { | |
return `${this._name} can ${this._specialAbility}`; | |
}; | |
} | |
} | |
// creating new instances of Hero | |
const IronMan = new Hero('Iron Man', 'fly'); | |
console.log(IronMan.getDetails()); // Iron Man can fly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the ES5 based approach, the
getDetails
function should be declared on theHero
prototype.For the ES6 based approach, the
getDetails
function should be a member function.