When using jquery, we often see or use a chain of methods, such as:
Copy Code code as follows:
$ ("#p1"). CSS ("Color", "red"). Slideup. Slidedown (2000);
This code means that the selector chooses an HTML tag with an ID of P1, the color turns red, then Slideup, then Slidedown.
Naturally, these methods can be written separately, but do not separate words not only have a good readability, the amount of code will be reduced, then why not?
This way of calling functions is called "chaining" in jquery, and the principle is simple: the ability to chaining a method call returns the object itself.
Here's a demo with Java code:
Do not use chaining:
Persion.java:
Copy Code code as follows:
public class Persion {
private int id;
private String name;
Private String PhoneNumber;
Private String address;
Public Persion () {
}
public void setId (int id) {
This.id = ID;
}
public void SetName (String name) {
THIS.name = name;
}
public void Setphonenumber (String phonenumber) {
This.phonenumber = PhoneNumber;
}
public void setaddress (String address) {
this.address = address;
}
public void Printid () {
System.out.println (this.id);
}
public void Printname () {
System.out.println (this.name);
}
public void Printphonenumber () {
System.out.println (This.phonenumber);
}
public void printaddress () {
System.out.println (this.address);
}
}
Test.java:
Copy Code code as follows:
public class Test {
public static void Main (string[] args) {
Persion persion1 = new Persion ();
Persion1.setid (3);
Persion1.setname ("John");
Persion1.setphonenumber ("1111111");
Persion1.setaddress ("US");
Persion1.printid ();
Persion1.printname ();
Persion1.printphonenumber ();
Persion1.printaddress ();
}
}
Use chaining:
Persion.java:
Copy Code code as follows:
public class Persion {
private int id;
private String name;
Private String PhoneNumber;
Private String address;
Public Persion () {
}
Public persion setId (int id) {
This.id = ID;
return this;
}
Public persion SetName (String name) {
THIS.name = name;
return this;
}
Public persion Setphonenumber (String phonenumber) {
This.phonenumber = PhoneNumber;
return this;
}
Public Persion setaddress (String address) {
this.address = address;
return this;
}
Public Persion Printid () {
System.out.println (this.id);
return this;
}
Public Persion Printname () {
System.out.println (this.name);
return this;
}
Public Persion Printphonenumber () {
System.out.println (This.phonenumber);
return this;
}
Public Persion printaddress () {
System.out.println (this.address);
return this;
}
}
Test.java:
Copy Code code as follows:
public class Test {
public static void Main (string[] args) {
Persion persion1 = new Persion ();
Persion1.setid (3). SetName ("John")
. Setphonenumber ("1111111"). Setaddress ("US");
Persion1.printid ()
. Printname ()
. Printphonenumber ()
. printaddress ();
}
}
So weird feeling ~ haha!