Believe that in JavaScript, C # have seen a lot of chained method calls, then, where the implementation of this kind of chain call principle, we have not carefully thought about it? There are a lot of examples in the JavaScript class library: JQuery, and in C #, where the use of lambda expressions and the addition of extension methods, so that the chain calls also see a lot.
First of all, just talk about the chain call in JavaScript, in fact, it is the use of the previously mentioned this.
varperson=function(name,age) { This. Name=name; This. Age=Age ; };//new Sayname method for prototype of the function personPerson.prototype.sayname=function() {alert ( This. Name); return This; };//new Sayage method for prototype of the function personPerson.prototype.sayage=function() {alert ( This. Age); return This; }//in the new method body for the function person.proetype, and finally, the returned this points to the object created with the function as the constructor//Thus, a chain call is formed NewPerson ("Jack", "20"). Sayname (). Sayage (); //Note that if the person ("Jack", "20") takes this type of call, at this point, this points to the window, in the browser environment
In addition, look at the implementation of chained calls in Java, C #, basically the same principle, the same is the use of this, however, in Java, C #, this represents the current object, and in JavaScript, this is determined by the runtime, not determined by the definition.
Roughly that is, in each method body, return this, method return value type is the current class type, you can implement this function.
Public classPerson { PublicString Name; Public intAge ; PublicPerson (String name,intAge ) { This. Name=name; This. Age=Age ; } PublicPerson sayname () {System.out.println ( This. Name); return This; } PublicPerson sayage () {System.out.println ( This. Age); return This; } Public Static voidMain (string[] args) {NewPerson ("Jack", 20). Sayage (). Sayname (); }}
Next, take a look at the new extension method in C #, which extends the method for objects of that type by means of a static class, which also specifies the first parameter of the method, which contains the This + type + parameter name, resulting in a large number of chained calls.
Brief talk on the principle of the general implementation of chaining method calls in JavaScript and Java