Skip to content

Instantly share code, notes, and snippets.

@salami162
Last active July 5, 2016 14:22
Show Gist options
  • Save salami162/5332074 to your computer and use it in GitHub Desktop.
Save salami162/5332074 to your computer and use it in GitHub Desktop.
How do you implement an extend function that takes an object and extends itwith new properties and makes it work on n levels of recursion? Basically, duplicating a jQuery extend.
/**
* Implement Foo Object.
* - Take a JSON object as an input parameter
* - Create a copy this JSON object as itself.
* - Chainable
*/
var foo = new Foo({
version : '1.0'
});
// add components
foo
.set({
type : 'Foo',
container : '#foo'
})
// add features
.addItem(['item1','item3'])
.addItem('item2');
/**
* Expect output
*/
foo = {
version : '1.0',
type : 'Foo',
container : '#foo',
items : ['item1', 'item3', 'item2']
}
/**
* Foo Object
*/
var Foo = function (config) {
var options = JSON.parse( JSON.stringify(config) );
options.items = [];
_.extend(this, options);
};
Foo.prototype.set = function (config) {
_.extend(this, config);
return this;
};
Foo.prototype.addItem = function (items) {
items = _(items).isArray() ? items : [items];
this.items = _.union(this.items, items);
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment