Note that there are some explanatory texts on larger screens.

plurals
  1. POsub object functions in javascript
    text
    copied!<p>I know you can create literal objects with subobjects and functions:</p> <pre><code>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()); </code></pre> <p>outputs: </p> <pre><code>1 2 3 </code></pre> <p>What I would like to do is do the same thing with methods in a object, something similar to:</p> <pre><code>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; } } }; }; </code></pre> <p>then i would expect: </p> <pre><code>var obj = new objType(); console.log(obj.func()); console.log(obj.level1.func()); console.log(obj.level1.level.func()); </code></pre> <p>to output:</p> <pre><code>1 2 3 </code></pre> <p>However, only the first console.log outputs before the script throws an error.</p> <p>Is there any way to have sub methods in Javascript?</p> <p>--edit--</p> <p>My goal is to create a class i can use for showing a box in the middle of the screen, for displaying messages, questions(to get a yes/no response), and forms. I was thinking a good way to structure it would be with sub methods, so that it could then be referenced with: </p> <pre><code>function box() { this.show = function(){ //multiple sub methods here } this.hide = function(){ //code to hide window here } } var aBox = new box(); aBox.show.message('the message'); aBox.hide(); aBox.show.question('the question'); aBox.hide(); </code></pre> <p>--edit-- thanks @Sean Vieira</p> <p>For completeness I'll put the modified version of my code here using his solution:</p> <pre><code>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()); </code></pre> <p>that outputs </p> <pre><code>1 2 3 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload