Grow your CSS skills. Land your dream job.

Better method for returning 'this' ?

  • Anonymous
    # January 5, 2014 at 11:32 pm

    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?

    __
    # January 6, 2014 at 12:12 am

    What do you think is inefficient about it?

    Anonymous
    # January 6, 2014 at 12:19 am

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

    # January 6, 2014 at 1:47 am

    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.

    Anonymous
    # January 6, 2014 at 5:30 am

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".