问题
I'm somewhat new to JavaScript/jQuery, but when I saw examples of method chaining it struck me as instantly familiar. Other interfaces like LINQ do something similar where the return type of a set of methods is the same as the type they operate on (TweetSharp does something very similar). Is this an example of fluent programming? Much of what I read about jQuery says that other libraries have "borrowed" this idea of method chaining - did the idea originate with jQuery?
回答1:
jQuery indeed heavily follows the builder pattern / fluent interface, but it is certainly not the pioneer of the design pattern at whole own. The other libraries likely followed after jQuery and borrowed its approach. It's just the fame jQuery has made which make it look like to originate with jQuery.
回答2:
Chaining alone does not make a fluent interface. The term "fluent interface" seems to have been popularized by Martin Fowler, one of the more prolific contemporary authors on software theory (though he did not invent the technique either).
Fowler clarifies that method chaining simply refers to methods that return the object reference, while a fluent interface is more akin to a domain specific language, and is (ideally) designed to flow more like natural language than code.
回答3:
JQuery certainly didn't invent of method-chaining; it was already possible in JavaScript and many other languages.
Method-chaining was perhaps legitimized in many people's eyes by JQuery. A lot of Java programmers still insist that an object's functions should only return other objects, never the object itself. As I recall 10 years ago I got modded off a Java mailing list for suggesting otherwise :)
来源:https://stackoverflow.com/questions/3398930/is-jquery-method-chaining-an-example-of-fluent-programming