Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can you method chain in vanilla javascript?

I did a quick google search but I didn't see anything, I would think vanilla js allows it, if jQuery is javascript and jQuery allows it, logically vanilla js would allow it right? I tired it in vanilla js to get a better understanding but it didn't work? Am I doing something wrong or is jQuery more complicated then just a javascript library?

if someone could explain this to me it would be great thanks

test={
      num: 0,
      add: function(){
                     this.num+=1;
                      return this.num;
             },
      subtract: function() {
                      this.num-=1;
                      return this.num;
             }
};

test.add().subtract()

2 Answers

You're right: this was harder than usual to find with a google search! I did find the answer but to be honest, the gains seem less than the effort required. This guy explains it better than I can: http://itridersblog.com/watch/5rwuKH-zdos

Your code would need to be something like the following:

var test = function () {

    var i = 0;

    var add = function (j) {
        i += j;
        return this;
      };

    var subtract = function (j) {
        i -= j;
        return this;
      };

    var print = function () {
        console.log(i);
      };

    return {
        add: add,
        subtract: subtract,
        print: print
    };
  };

var x = test();

then you can run:

x.add(3).subtract(2).print();

Thanks man!

Heya brother, remember to put the language after them thar ticks. Makes it a heck of a lot easier to read ;). Fixed.

Good video too, thanks for the link and great answer :)

Cheers,

Huck - :sunglasses:

  • huckleberry Thanks, the markdown force was not with me.

Another way is as follows. But I'm not sure if this works in all situations:

Instead of this:

var people = helper.getPeople();
var bob = people.find("bob");
var email = bob.getEmail();

You could do this:

var email = helper.getPeople().find("bob").getEmail();

Upon comparing someone else's code to my own to solve the same challenge at freecodecamp, I noticed that method chaining when assigning to a variable works. I don't know why this isn't at the top of google. Like seriously, when I google "JavaScript Method Chaining". I need this to come up first.