Background
I have a function that takes a config
object as an argument. Within the function, I also have default
object. Each of those objects contains properties that essentially work as settings for the rest of the code within the function. In order to prevent having to specify all of the settings within the config
object, I use jQuery's extend
method to fill in a new object, settings
with any default values from the default
object if they weren't specified in the config
object:
var config = {key1: value1};
var default = {key1: default1, key2: default2, key 3: default 3};
var settings = $.extend(default, config);
//resulting properties of settings:
settings = {key1: value1, key2: default2, key 3: default 3};
Problem
This works great, but I'd like to reproduce this functionality without the need for jQuery. Is there an equally elegant (or close to) means to do this with plain ol' javascript?
Edit: Non-Duplicate Justification
This question is not a duplicate of the "How can I merge properties of two JavaScript objects dynamically?" question. Whereas that question simply wants to create an object that contains all of the keys and values from two separate objects - I specifically want to address how to do this in the event that both objects share some but not all keys and which object will get precedence (the default) for the resulting object in the event that there are duplicate keys. And even more specifically, I wanted to address the use of jQuery's method to achieve this and find an alternative way to do so without jQuery. While many of the answers to both questions overlap, that does not mean that the questions themselves are the same.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…