0

I recently started learning AngularJS using the Google documentation, and I ran into a notation I am unfamiliar with.

The general syntax that I am confused with is as follows:

 someObject(someParams)
.SomeFunction()
.SomeFunction()
.SomeFunction()

The problem is that typically I am used to seeing

SomeObject.someFunction()
SomeObject.someFunction()
SomeObject.someFunction()

Can someone please clarify what is going on here? Am I missing something? If it helps at all, I teach Java Programming and am very good with C# and Java so maybe that can help someone gear up an answer for me.

stark
  • 2,246
  • 2
  • 23
  • 35
  • 1
    Chaining Methods. Plenty of tutorials out there explaining how it works. – epascarello Feb 04 '16 at 20:58
  • so this is called "chaining methods"? do you have a tutorial you would recommend? – Kurtis Durtis Feb 04 '16 at 20:59
  • The [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) is one way to do this, where the object modifies and returns itself or returns a copy. – ssube Feb 04 '16 at 21:03
  • promise chains. It's an adjustment coming from Java but it's at the heart of the asynchronous power of JavaScript. Here's the angular.js documentation: https://docs.angularjs.org/api/ng/service/$q. I've also found this overview summary helpful (though its for a different promise library): https://github.com/kriskowal/q – obi1 Feb 04 '16 at 21:04

1 Answers1

0

This is method chaining, and it's common in many libraries, including AngularJS, and jQuery.

If a method is not used to return new information (such as getting the value of an input, or an element attribute), the normal behavior is for it to return the same object that it was called on. This way, instead of having to say SomeObject. repeatedly, you can simply call the next method on the return value of the previous method. Because of this, the chained methods are equivalent to the code you're used to seeing.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Barmar
  • 741,623
  • 53
  • 500
  • 612