-
-
Save junwatu/9f0055d3dd7cfc398f04 to your computer and use it in GitHub Desktop.
ES6 defaults / overrides pattern
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
| // The defaults / overrides pattern in ES6 | |
| // This *looks like* it should work, but | |
| // prints, "yay, undefined" | |
| /* | |
| let defaults = { | |
| bar: 'no', | |
| baz: 'works!' | |
| }; | |
| function foo ({ bar, baz } = defaults) { | |
| return(`${bar}, ${baz}`); | |
| } | |
| console.log(foo({ | |
| bar: 'yay' | |
| })); | |
| */ | |
| // So you really have to do this: | |
| let defaults = { | |
| bar: 'no', | |
| baz: 'works!' | |
| }; | |
| function foo (options) { | |
| let settings = Object.assign({}, defaults, options); | |
| let { bar, baz } = settings; | |
| return(`${bar}, ${baz}`); | |
| } | |
| console.log(foo({ | |
| bar: 'yay' | |
| })); | |
| // Equivalent to ES5: | |
| // This bit needs to be polyfilled, | |
| // Or use $.extend(), _.extend(), | |
| // lodash/object/assign aka _.assign() | |
| // or equivalent. | |
| var assign = Object.assign; | |
| var defaults2 = { | |
| bar: 'no', | |
| baz: 'works!' | |
| }; | |
| function foo2 (options) { | |
| var settings = Object.assign({}, defaults2, options), | |
| bar = options.bar, | |
| baz = options.baz; | |
| return(bar + ', + ' baz); | |
| } | |
| console.log(foo2({ | |
| bar: 'yay' | |
| })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment