Jessica Jessica - 5 months ago 16
Javascript Question

Merge default with user defined settings

I'm trying to create a plugin with settings. There will be default settings, and user defined settings. I will have to somehow merge the two in an

object
. I tried the following:

JSFiddle


function MyPlugin(options) {
if (typeof optoins === null || typeof options !== 'object') options = {};

var defaults = {
prop1: true,
prop2: false,
prop3: 0,
prop4: 100,
}
// Set default options
for (var name in defaults) {
!(name in options) && (this.options[name] = defaults[name]);
}
}
var test = new MyPlugin();





But I get an error saying:


Uncaught TypeError: Cannot set property 'prop1' of undefined


What's the correct, most efficient way to merge the default and user defined settings?

Answer

I think you could be looking at something like this.

function MyPlugin(options) {
    var options = options || {};

    if (typeof userOpt !== 'object') {
        options = {};
    }

    var defaults = {
        prop1: true,
        prop2: false,
        prop3: 0,
        prop4: 100
    };

    // Set default options
    for (var name in defaults) {
        defaults[name] = options.hasOwnProperty(name) ? options[name] : defaults[name];
    }
}

MyPlugin({
    prop1: false,
    prop4: 300
});

So if MyPlugin() is called with a null then userOpt would be an empty object {}.

Output:

{"prop1":false, "prop2":false, "prop3":0, "prop4":300}

The .hasOwnProperty is just checking to see if it has been set by the user or not, if yes then go with the user's option otherwise do the default.

hasOwnProperty: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.