Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Better method for returning 'this' ?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #159727
    Anonymous
    Inactive

    Consider the following code snip: jsFiddle

    Is there a more efficient way for returning an object instead of having to return this; after each method? I’m aware of jQuery’s return this.each, but I don’t think that is applicable here.

    Any help is welcome.

    Edit: I found a partial solution by chaining each method in a function called all, and then calling it on the object. Notice I still have to return this after each method though. Any way to do this only once?

    #159728
    __
    Participant

    What do you think is inefficient about it?

    #159730
    Anonymous
    Inactive

    @traq

    I guess I’m more concerned with the cleanliness of the code. Having to write return this; after every function seems redundant in my opinion. Perhaps that’s the only way of doing it. I’m still trying to get a solid grasp of javascript and often wonder if I’m writing it properly.

    #159731
    jamygolden
    Member

    return this is what is needed to be done if you’re looking to chain.

    You could also look into what Lea Verou did on Chainvas.

    #159744
    Anonymous
    Inactive

    Okay, thanks for the suggestion and help. I have one final question regarding a similar issue.

    Have a look at this working fiddle. If I change the init function to something like this fiddle, the code fails to execute, unless I also change this.test(); to myObject.test(); inside function one.

    Is there anyway to call the test function using this instead of myObject?

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.