Last active
March 21, 2019 04:11
-
-
Save noizbuster/69532433ea9e6f74e47e19e88edd7bf9 to your computer and use it in GitHub Desktop.
Example for destructuring
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
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment | |
class TestClass { | |
constructor({a = 1, b = 2, c, d, ...extra} = {d: 4}) { | |
this.data = {a, b, c, d}; | |
this.extra = extra; | |
} | |
toString() { | |
console.log(`a = ${this.data.a}, b = ${this.data.b}, c = ${this.data.c}, d = ${this.data.d}, extra = ${this.extra}`) | |
} | |
} | |
const noparam = new TestClass(); | |
console.log('no param', noparam); | |
const onlya = new TestClass({a: 3}); | |
console.log('only a', onlya); | |
const addc = new TestClass({c: 3}); | |
console.log('add c', addc); | |
const withExtra = new TestClass({ex: 3}); | |
console.log('with extra', withExtra); | |
/* | |
The result of above code | |
noparam TestClass { data: { a: 1, b: 2, c: undefined, d: 4 }, extra: {} } | |
onlya TestClass { data: { a: 3, b: 2, c: undefined, d: undefined }, extra: {} } | |
addc TestClass { data: { a: 1, b: 2, c: 3, d: undefined }, extra: {} } | |
withExtra TestClass { data: { a: 1, b: 2, c: undefined, d: undefined }, extra: { ex: 3 } } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment