John Smith
John Smith

Reputation: 81

Three dimensional objects in JavaScript

I'm trying to create three dimensional objects in JavaScript. I want to be able to run something like this:

object1().object2().object3();

but i don't want "object3()" to be able to be accessed like this:

object1().object3();

When i tried this:

function object1(){
    alert("object 1");
    function object2(){
        alert("object 2");
        function object3(){
            alert("object 3");
        }
    }
}

It runs the first alert, but then chrome gives me this error:

TypeError: Object #<object1> has no method 'object2'

and when i tried this:

function object1(){
    alert("object 1");
    this.object2 = function(){
        alert("object 2");
        this.object3 = function(){
            alert("object 3");
        }
    }
}

it runs the first two and then chrome gives me this error:

TypeError: Cannot call method 'object3' of undefined

Upvotes: 2

Views: 325

Answers (2)

Adrian
Adrian

Reputation: 46532

To do method call chaining, you need to return a reference to this:

function object1(){
    alert("object 1");
    this.object2 = function(){
        alert("object 2");
        this.object3 = function(){
            alert("object 3");
        }
        return this;
    }
    return this;
}

(Working) Fiddle here: http://jsfiddle.net/MmJjR/

(As a side note, this is not a "three dimensional object". Objects aren't like arrays. These are nested objects, wherein each has a reference to the next "child" object. It was easy to understand what you meant, just thought I'd toss a terminology tip out there.)

Upvotes: 4

StuR
StuR

Reputation: 12228

object1 = function(){
    console.log("object 1");
    this.object2 = function(){
        console.log("object 2");
        this.object3 = function(){
            console.log("object 3");
        }
        return this;
    }
    return this;
}

object1().object2().object3()

Maybe something like this?

http://jsfiddle.net/rd13/T2EG2/

Upvotes: 1

Related Questions