I know that you can create literals with subobjects and functions:
var obj = {
val : 1,
level1 : {
val : 2,
val2 : 3,
func : function(){
return this.val2
}
}
}
console.log(obj.val);
console.log(obj.level1.val);
console.log(obj.level1.func());
outputs:
1
2
3
What I would like to do is do the same with the methods in the object, something similar to:
function objType() {
this.val = 1;
this.func = function(){
return this.val;
}
this.level1 = function(){
this.val = 2;
this.func = function(){
return this.val;
}
this.level2 = function(){
this.val = 3;
this.func = function(){
return this.val;
}
}
};
};
then I would expect:
var obj = new objType();
console.log(obj.func());
console.log(obj.level1.func());
console.log(obj.level1.level.func());
for output:
1
2
3
However, only the first console.log exits before the script throw an error.
Is there a way to have helper methods in Javascript?
- edit -
My goal is to create a class that I can use to display a window in the middle of the screen, to display messages, questions (to get a yes / no answer) and forms. I thought a good way to structure this would be with helper methods, so that it could be referenced:
function box() {
this.show = function(){
}
this.hide = function(){
}
}
var aBox = new box();
aBox.show.message('the message');
aBox.hide();
aBox.show.question('the question');
aBox.hide();
- edit-- thanks @Sean Vieira
For completeness, I will put a modified version of my code here, using its solution:
function objType() {
this.val = 1;
this.func = function(){
return this.val;
}
this.level1 = {
val : 2,
func : function(){
return this.val;
},
level2 : {
val : 3,
func : function(){
return this.val;
}
}
}
var obj = new objType();
console.log(obj.func());
console.log(obj.level1.func());
console.log(obj.level1.level.func());
which outputs
1
2
3