3

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.

2 Answers 2

8

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();
Sign up to request clarification or add additional context in comments.

2 Comments

a quick comment for clarification since you said that you are new to JS, this is not a JS feature, you can achieve this in different programming languages by returning an object which has other methods you can invoke
Yep. In fact, wikipedia has example in C#, C++, Java and PHP. en.wikipedia.org/wiki/Method_chaining
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.