2

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

2 Answers 2

4

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.)

Sign up to request clarification or add additional context in comments.

Comments

1
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.