When using jQuery, we often see or use method chains, such as:
Copy the code code as follows:
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
The meaning of this code is that the selector selects the html tag with id p1, the color turns red, then slides up, and then slides down.
Naturally, these methods can be written separately, but if they are not separated, it will not only have good readability, but the amount of code will also be reduced, so why not?
This way of calling functions is called "Chaining" in jQuery, and the principle is also very simple: the method that can be chained returns the object itself after being called.
Below is a demonstration using java code:
Without chaining:
Persion.java:
Copy the 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 the 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");
person1.setAddress("US");
session1.printId();
session1.printName();
persion1.printPhoneNumber();
person1.printAddress();
}
}
Using chaining:
Persion.java:
Copy the 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 the code code as follows:
public class Test {
public static void main(String[] args) {
Persion persion1 = new Persion();
person1.setId(3).setName("John")
.setPhoneNumber("1111111").setAddress("US");
session1.printId()
.printName()
.printPhoneNumber()
.printAddress();
}
}
What a weird feeling~haha!