Creating a config for a function in JavaScript
I want my JavaScript class to be configurable from the outside. So, I created a private config
-property and a l开发者_JS百科oadConfig
-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 :) ).
It's overwritten because you're telling it to overwrite with this line in your loadConfig
method:
config = loadConfig;
In order to preserve any values that loadConfig
does not explicitly change, you'll have to loop through all of the properties in loadConfig
and assign them individually:
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];
}
}
}
};
精彩评论