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.
asked Aug 12, 2011 at 18:07
0xAX
22k26 gold badges124 silver badges211 bronze badges
2 Answers 2
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();
answered Aug 12, 2011 at 18:11
Alex Wayne
188k52 gold badges328 silver badges363 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
K''
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
Alex Wayne
Yep. In fact, wikipedia has example in C#, C++, Java and PHP. en.wikipedia.org/wiki/Method_chaining
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.
answered Aug 12, 2011 at 18:11
Adrian Rodriguez
3,2672 gold badges26 silver badges34 bronze badges
Comments
lang-js