Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created February 3, 2014 04:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iammerrick/8778977 to your computer and use it in GitHub Desktop.
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.
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.
@rwaldron
Copy link

rwaldron commented Feb 3, 2014

If the defaults will never change you can avoid the redeclaration and define it outside of class Person :)

@iammerrick
Copy link
Author

So true. Thanks man. :-)

@iammerrick
Copy link
Author

@rwaldron This gist was inspired by your code review of our Diary.js code :-)

@rwaldron
Copy link

rwaldron commented Feb 3, 2014

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