To remove tedious code i would like to create a function to simplify it.
So to change the settings that i stored in an object, I created this.
var settings = {
color : 'red'
//one of many settings
};
alert(settings.color); // returns red
function changeValue(property, value){
settings.property = value;
}
changeValue('color', 'blue');
alert(settings.color); // still return red
it seems like its treated as a string instead.
And if i try this:
function changeValue(object, value){
object = value;
}
changeValue(settings.color, 'blue');
it would only give the function the value which is 'red'.
and this:
changeValue('settings.color', 'blue');
would not work obviously.
So how do i solve this ? How do i pass down a variable to a function but not its value so it can be altered ?
Note: the function is simplified for now, but would contain a lot more magic when it works.
2 Answers 2
Pass the object and the name of the property that you want to change as separate arguments:
function changeValue(obj, prop, value) {
obj[prop] = value;
}
changeValue(settings, "color", "blue");
Assuming var prop = "color" then obj[prop] is equivalent to obj.color. The first notation allows you to dynamically specify the property that should be changed.
1 Comment
when you do settings.color you get a value, rather than object. You'd have to do something like
function changeValue(object, field, value){
object[field] = value;
}
used like
changeValue(settings, 'color', 'blue')
which may not actually reduce time for you at all..
EDIT:: I have made this function for you. But please.. Don't ever use it.
var settings = {
color : "blue"
}
function setField(str, value){
var args = str.split(".").reverse();
var obj = window[args.pop()];
while(args.length - 1 > 0)
obj = obj[args.pop()]
obj[args.pop()] = value;
}
alert(settings.color);
setField("settings.color", "red");
alert(settings.color);