问题
So... messing around in JavaScript with an idea that's new to me, having methods of an Object return the Object of which they are methods; this then leads to chainability. My question, then: how can this be useful? I threw this together to test the fundamental workings:
<script>
MathChain = function()
{
this.pass = function()
{
this.multiply = eval(arguments.join('*'));
this.add = eval(arguments.join('+'));
return this;
}
}
m = new MathChain().pass(5, 10, 20).multiply; // 1000
a = new MathChain().pass(5, 10, 20).add; // 35
</script>
That's obviously not a viciously efficient instance in which one would use this concept, so could you point me to something that does do so properly (aside from jQuery, please)?
回答1:
Well, here is a not very real-world applicable example, but I think you'll get the idea. If allows you to do a number of different operations on an object, and provides convenience.
var truck = function() {
this.turnLeft = function {
// turn left
return this;
}
this.turnRight = function {
// turn right
return this;
}
this.goReallyFast = function {
// go fast!
return this;
}
};
// My get-away plan
var myTruck = new truck();
myTruck.turnLeft().turnRight().goReallyFast();
回答2:
For a very different (non-OO) example, chaining is somewhat analogous to Unix pipelines. Each step of a Unix pipe returns the full (modified) content, suitable for sending on to the next step:
cat file1 file2 | sort -n | awk '{print $2}' | sed 's/@/ at /g'
回答3:
Fluent interface - http://en.wikipedia.org/wiki/Fluent_interface
Yea I think it could be very useful but like any design pattern should only be used when needed
Edit: here is twitter client api in c# using a fluent interface - http://code.google.com/p/tweetsharp/
回答4:
One example where it's useful is with a slight variation on your problem — instead of returning the same object, you design the object to be immutable. Then your functions will all return a new instance of the same type, but with the properties already set appropriately.
This has many practical applications, especially in the realm of functional programming.
回答5:
While it doesn't work in the same way as your example (TBH I've never seen it done that way before), jquery considers "chaining" to be very useful, and jquery is pretty much the yardstick these days when it comes to JS web frameworks... so yeah :-)
回答6:
I found this question while searching for a general solution to making methods chainable, after they are defined. Here's what I came up with. I am a JavaScript neophyte; buyer beware.
makeChainable = function() {
var receiver = arguments[0]
for (var i = 1; i < arguments.length; i++) {
functionName = arguments[i];
(function() {
wrapped = receiver[functionName];
receiver[functionName] = function() {
wrapped.apply(receiver, arguments);
return receiver;
}
})();
}
}
daisy = {
name: 'Daisy',
moo: function() { console.log(this.name + " moos!") }
}
makeChainable(daisy, 'moo');
daisy.moo().moo().moo();
回答7:
In JavaScript this comes up all the time when navigating the DOM. In particular when trying to wade your way through a bunch of elements that don't have ids.
For example there was a question on SO regarding finding the first element of a table. It can involve a lot of loops or chained commands.
回答8:
JavaScript chaining can be very useful if you want to preform a series of actions on a single object. I agree with Michael Luton below, chaining should be handled with care. If you add one or two chained methods onto an object that is still readable. If you start adding four, five, or even nine, then your code becomes harder not only to read but to maintain.
回答9:
All the kids love chaining. However, in my experience it should be used with care since it can decrease the readability of the code. In other words, do what makes sense to you and can be easily understood by other programmers who have a basic familiarity with the concept..
来源:https://stackoverflow.com/questions/603499/javascript-object-method-chaining-useful