Created
November 12, 2018 14:26
-
-
Save emfluenceindia/d8373aaf65f83f0c780c328be9cb34b4 to your computer and use it in GitHub Desktop.
Default Parameters in ES6 - in classes
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
/** | |
A simple example of default parameter handling inside a JavaScript class which uses a constructor | |
*/ | |
class paramValueExample { | |
constructor(x, y) { | |
this.x = 25; | |
this.y = 50; | |
this.fruits = ['banana', 'apple', 'grapes']; | |
this.persons = { | |
person: { | |
name: 'Bob Martyn', | |
age: 47, | |
location: 'Australia' | |
} | |
}; | |
} | |
handleDefaultParamters = (xp = 10, yp = 20, objPersons = {}) => { | |
console.log(xp, yp); | |
this.x = xp; | |
this.y = yp; | |
console.log(this.persons); | |
this.persons = objPersons; | |
console.log(`${xp + yp}`, this.fruits, this.persons); | |
} | |
} | |
const newPersons = { | |
person: { | |
name: 'Jacob Schwartz', | |
age: 38, | |
location: 'USA' | |
} | |
} | |
/** | |
Instantiate the class and create an objet of it | |
*/ | |
const pve = new paramValueExample(); | |
/** | |
Call the function and send some values and skip an intermediate parameter. | |
The keyword 'undefined' forces ES6 to use the default value set for that parameter. | |
*/ | |
pve.handleDefaultParamters(35, undefined, newPersons); | |
// More explanations could be found at | |
https://gist.github.com/emfluenceindia/cbb89527c47f148bdff74cd50e60c5a8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment