I want my JavaScript class to be configurable from the outside. So, I created a private config-property and a loadConfig-method. My problem is, that when I load a config, it overwrites the config-property completely and not just the properties 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 I load a custom config
<script type="text/javascript">
var config = {
group: {
groupParam: "newValue"
}
};
MyClass.loadConfig(config);
</script>
I want config.param to still be “value”, while config.group.groupParam is “newValue”.
Currently, the object is overwritten and after loadConfig(), config.param doesn’t exist anymore.
If you don’t want to reinvent the wheel, jQuery has a great function called
$.extend()which seems to be what you need.You can check it out in the jQuery 1.6.1 source for example ( Ctrl + F and “extend” => been a long time since I’ve been waiting to use these keyboard things once 🙂 ).