简体   繁体   中英

java script call methods from another methods

I'm new in js.

I see code example:

foo.bar().baz()

How described foo bar and baz that we can call so?

Thank you.

What are you are probably after is called chaining. A method can return the object it's running on this , so that another method may be called.

var foo = {
  bar: function() {
    doStuff();
    return this;
  },

  baz: function() {
    doOtherStuff();
    return this;
  }
};

foo.bar().baz();

This is exactly how jQuery works, in order to allow things like:

$('#foo')
  .html('<p>hi</p>')
  .addClass('selected')
  .css('font-size', '24px')
  .show();

So let's say you had an object foo with two methods: bar and bad. The implementation of bar would be like this: function bar() { /* do work */ return this; } That returns foo itself so you can call baz since it's defined in foo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM