Edgar Edgar - 4 months ago 7
Javascript Question

Javascript call one object method after another

I have this object:

const Foo = {

bar(x) {

},

baz(x) {

},

}


How can I rewrite this object to be able to call it's methods like this:

Foo.bar(x).baz(y);


instead of calling them like this:

Foo.bar(x);
Foo.baz(y);





Like in the
jQuery
where you can call one function after another...

$('bac').addClass('x').removeClass('y');

Answer

You should return this at the end of each function. In this context this refers to the Foo object itself.

const Foo = {

  bar(x) {
      return this;
  },

  baz(z) {
      return this;
  }

}

Example:

Foo.bar(x).baz(z);

is executed as:

Foo.bar(x) // <-- returns 'Foo'
   .baz(z) // <-- call 'baz' function of 'Foo'
Comments