Created
February 3, 2014 04:47
-
-
Save iammerrick/8778977 to your computer and use it in GitHub Desktop.
The old $/_.extend, the old Mootools options, the iconic Object.prototype.extend... Yes merging defaults with configuration using Object.assign.
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
class Person { | |
constructor(config = {}) { | |
var defaults = { | |
name: 'Unknown', | |
age: 23 | |
}; | |
[defaults, config].reduce(Object.assign, this); | |
} | |
} | |
var me = new Person({ name: 'Merrick' }); | |
console.log('The person is named %s and is %d years old.', me.name, me.age); | |
// Logs The person is named Merrick and is 23 years old. | |
So true. Thanks man. :-)
@rwaldron This gist was inspired by your code review of our Diary.js code :-)
I must give proper credit where it's due: @ericf came up with this pattern while sitting next to me during a TC39 meeting last year: https://gist.github.com/ericf/3751340 :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the defaults will never change you can avoid the redeclaration and define it outside of
class Person
:)