Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active April 26, 2023 16:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drenther/e2e3d95930b2ed3d3560ce0985fd3421 to your computer and use it in GitHub Desktop.
Save drenther/e2e3d95930b2ed3d3560ce0985fd3421 to your computer and use it in GitHub Desktop.
Creational Pattern - Constructor
// 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
@brodeuralexis
Copy link

For the ES5 based approach, the getDetails function should be declared on the Hero prototype.
For the ES6 based approach, the getDetails function should be a member function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment