在使用jQuery时候,我们经常会看到或者使用到方法链,例如:
自然是可以将这几个方法分开写,但是不分开的话不仅有很好的易读性,代码量也会有减少,那么何乐而不为?
这种调用函数的方式在jQuery中称为“Chaining”,原理也很简单:能够chaining的方法调用后返回对象本身即可。
下面用java代码做个演示:
不使用chaining:
Persion.java:
}
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);
}
}
Persion.java:
}
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;
}
}
新闻热点
疑难解答