开发者

java script call methods from another methods

开发者 https://www.devze.com 2023-03-27 14:26 出处:网络
I\'m new in js. I see code example: foo.bar().baz() How described foo bar and baz that we can call so?开发者_开发问答

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

精彩评论

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