Created
January 6, 2015 06:57
-
-
Save pbojinov/8f3765b672efec122f66 to your computer and use it in GitHub Desktop.
A vanilla JS extend() function - http://gomakethings.com/vanilla-javascript-version-of-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
var defaults = { | |
number: 1, | |
bool: true, | |
magic: 'real', | |
animal: 'whale', | |
croutons: 'delicious' | |
}; | |
var options = { | |
number: 2, | |
magic: 'real', | |
animal: 'porpoise', | |
bool: false, | |
random: 42 | |
}; | |
var settings = extend(defaults, options); | |
console.log(settings); | |
// Returns: Object{animal: "porpoise", bool: false, croutons: "delicious", magic: "real", number: 2, random: 42} |
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
/** | |
* Merge defaults with user options | |
* @private | |
* @param {Object} defaults Default settings | |
* @param {Object} options User options | |
* @returns {Object} Merged values of defaults and options | |
*/ | |
var extend = function ( defaults, options ) { | |
var extended = {}; | |
var prop; | |
for (prop in defaults) { | |
if (Object.prototype.hasOwnProperty.call(defaults, prop)) { | |
extended[prop] = defaults[prop]; | |
} | |
} | |
for (prop in options) { | |
if (Object.prototype.hasOwnProperty.call(options, prop)) { | |
extended[prop] = options[prop]; | |
} | |
} | |
return extended; | |
}; |
How about this.. https://gist.github.com/bhavyaw/25b115603630ebf2271d
How about this little code down here:
function extendDefaults(source, properties) {
var property;
for(property in properties) {
if(properties.hasOwnProperty(property)) {
source[property] = properties[property];
}
}
return source;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated version:
Takes in what ever amount of arguments