Creating a configuration for a function in JavaScript

I want my JavaScript class to be configured externally. So, I created a private config-property and loadConfig-method. My problem is that when loading the configuration, it completely overwrites the configuration property, and not just the properties that I defined.

(function() {
var config = {
    param: value,
    group: {
        groupParam: value
    }
};
function MyClass() {
    this.loadConfig = function(loadConfig) {
        if (typepof loadConfig == "undefined" || typeof loadConfig == "null")
            return;
        else
            config = loadConfig;
    };  
}
window.MyClass = new MyClass();
})();

When loading user configuration

<script type="text/javascript">
    var config = {
        group: {
            groupParam: "newValue"
        }
    };

    MyClass.loadConfig(config);
</script>

I want it to config.paramremain "value", and config.group.groupParam- "newValue".

Currently, the object is overwritten and after loadConfig(), config.paramno longer exists.

+3
source share
2 answers

, jQuery $.extend(), , , .

jQuery 1.6.1 (Ctrl + F "extend" = > , , :)).

+3

, , loadConfig:

config = loadConfig;

, loadConfig , loadConfig :

this.loadConfig = function (loadConfig) {
    if (typeof loadConfig == "undefined" || typeof loadConfig == "null") {
        return;
    } else {
        var x;
        for (x in loadConfig) {
            if (Object.prototype.hasOwnProperty.call(loadConfig, x)) {
                config[x] = loadConfig[x];
            }
        }
    }
};
+1

All Articles