Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sub object functions in javascript

Tags:

javascript

I know you can create literal objects 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 thing with methods in a 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());

to output:

1
2
3

However, only the first console.log outputs before the script throws an error.

Is there any way to have sub methods in Javascript?

--edit--

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:

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();

--edit-- thanks @Sean Vieira

For completeness I'll put the modified version of my code here using his 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());

that outputs

1
2
3
like image 825
AsherMaximum Avatar asked Sep 12 '26 18:09

AsherMaximum


1 Answers

you can do this easily with chaining

function Box() {
    this.show = function(){
       //your code goes here
       return this;

    },
    this.message = function(message){
       //code goes here
       return this;
    }
  }

var aBox = new Box();
aBox.message('the message').show()
like image 110
Sebastian Otto Avatar answered Sep 15 '26 06:09

Sebastian Otto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!