开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜