Last active
July 5, 2016 14:22
-
-
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.
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
/** | |
* 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'] | |
} |
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
/** | |
* 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