clarkk clarkk - 26 days ago 11
Javascript Question

multi dimensional object

how can you make a multi dimensional object??

function tst(){
this.a = function(){
alert(this.b.abc.c());
};

this.b = function(){

};
}
var obj = new tst();
obj.b.abc = function(){
this.c = function(){
return 'hello world';
};
};

obj.a();

Answer

The problem is with this code:

obj.b.abc = function(){
    this.c = function(){
        return 'hello world';
    };
};

Calling the abc function will not create a obj.b.abc.c function, but a obj.b.c function. Therefore, this.b.abc.c() throws an error because such a function doesn't exist.


This will make it work:

function tst() {
    this.a = function() {
        alert( this.b.abc.c() );
    };

    this.b = function() {

    };
}

var obj = new tst();

obj.b.abc = function() {
    this.abc.c = function() { // <--- NEW 
        return 'hello world';
    };
};

obj.b.abc(); // <--- NEW
obj.a();

Live demo: http://jsfiddle.net/vgpNU/