I keep meaning to put together quickviews of languages I use, almost like cheatsheets, but like a pocket guide overview of language syntax and uses. I recently brushed up on es6 classes.
So here’s my first attempt at a quickview: es6 classes
Basics
Constructors
1 2 3 4 5 | class NameOfClass { constructor(args) { ... } } |
Setting class level variables:
Adding parameters to this
1 2 3 4 5 | class NameOfClass { constructor(name) { this.name = name; } } |
Methods
Add a method to an es6 class
1 2 3 4 5 6 7 8 9 | class NameOfClass { constructor(name) { this.name = name; } methodName() { return "Hi " + this.name + "!" } } |
Default values for arguments
Set a default value for an argument in an es6 class
1 2 3 4 5 | ... constructor(name = "Default") { this.name = name; } ... |
Interpolation
Template strings and interpolating variables (injecting a variable):
You use ${…} and backtick syntax `..`
1 2 3 4 5 6 7 8 9 | class NameOfClass { constructor(name) { this.name = name; } methodName() { return `Hi ${ this.name } !` } } |
Note: You can put any kind of valid javascript in the interpolation, including methods.
Advanced
Extending
Extend one class with another class in es6 classes.
1 2 3 | class OtherClass extends NameOfClass { ... } |
Call parent class
Referencing the parent class constructor with super(…);
1 2 3 4 5 6 | class OtherClass extends NameOfClass { constructor(originalClassArg, newClassArg) { super(originalClassArg); // You are calling the original class' constructor this.newClassArg = newClassArg; } } |
Overriding
Extending a parent class method without overriding it:
1 2 3 4 5 6 7 8 9 10 11 12 | class OtherClass extends NameOfClass { constructor(originalClassArg, newClassArg) { super(originalClassArg); this.newClassArg = newClassArg; } methodName() { let methodValue = super.methodName(); ... // more logic, do something with methodValue perhaps .. } } |
References:
Recommended Course:
https://completereactcourse.com
Read more on template strings:
https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings