i have some javascript class someClass and have initialization function init which check constructor params. Object with this params are rather huge and this function became too large.
function SomeClass (paramObj) {
this.inputHourId;
this.inputHourName;
this.inputHourValue;
......
......
this.Init = function (paramObj) {
if (typeof paramObj.hourOptions.inputName == "undefined") {
this.inputHourName = "default_name";
} else {
this.inputHourName = paramObj.hourOptions.inputName;
}
if (typeof paramObj.hourOptions.inputValue == "undefined") {
this.inputHourValue = "default_value";
} else {
this.inputHourValue = paramObj.hourOptions.inputValue;
}
......
......
......
}
this.Init(paramObj);
}
To avoid code duplication and make it more readable i decide to create function which will do var initialization with check
this.initVar = function (veriable, value) {
if (typeof value == "undefined") {
veriable = "some_default_value";
} else {
veriable = val;
}
}
after adding initVar function, my Init function should look like that:
this.Init = function (paramObj) {
// Input hour initialization
this.initVar(this.inputHourId, paramObj.hourOptions.inputId);
this.initVar(this.inputHourName,
paramObj.hourOptions.inputName);
this.initVar(this.inputHourValue, paramObj.hourOptions.inputValue);
....
....
....
}
but after that class vars this.inputHourName are still undefined
Now the question. How can I init my class property with the help of function? Or how can i transmit class property like function parametr?
That’s because when you pass
this.inputHourIdtoinitVar()it will make a copy of the variable when it’s being updated; that’s not what you want.You can rewrite
initVar()to this; it uses the name of the variable as a string rather than the variable itself. Then it usesthis[variable]to update the actual instance variable.Then, you call it like: