在使用jQuery时候,我们经常会看到或者使用到方法链,例如:
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
这段代码的意思是选择器选择id为p1的html标签,颜色变红,之后slideup,再slidedown。
自然是可以将这几个方法分开写,但是不分开的话不仅有很好的易读性,代码量也会有减少,那么何乐而不为?这种调用函数的方式在jQuery中称为“Chaining”,原理也很简单:能够chaining的方法调用后返回对象本身即可。
下面用java代码做个演示:
Person.java
publicclassPersion{ privateintid; privateStringname; privateStringphoneNumber; privateStringaddress; publicPersion(){ } publicvoidsetId(intid){ this.id=id; } publicvoidsetName(Stringname){ this.name=name; } publicvoidsetPhoneNumber(StringphoneNumber){ this.phoneNumber=phoneNumber; } publicvoidsetAddress(Stringaddress){ this.address=address; } publicvoidprintId(){ System.out.println(this.id); } publicvoidprintName(){ System.out.println(this.name); } publicvoidprintPhoneNumber(){ System.out.println(this.phoneNumber); } publicvoidprintAddress(){ System.out.println(this.address); } }
Test.java
publicclassTest{ publicstaticvoidmain(String[]args){ Persionpersion1=newPersion(); persion1.setId(3); persion1.setName("John"); persion1.setPhoneNumber("1111111"); persion1.setAddress("US"); persion1.printId(); persion1.printName(); persion1.printPhoneNumber(); persion1.printAddress(); } }
使用chaining:
Person.java
publicclassPersion{ privateintid; privateStringname; privateStringphoneNumber; privateStringaddress; publicPersion(){ } publicPersionsetId(intid){ this.id=id; returnthis; } publicPersionsetName(Stringname){ this.name=name; returnthis; } publicPersionsetPhoneNumber(StringphoneNumber){ this.phoneNumber=phoneNumber; returnthis; } publicPersionsetAddress(Stringaddress){ this.address=address; returnthis; } publicPersionprintId(){ System.out.println(this.id); returnthis; } publicPersionprintName(){ System.out.println(this.name); returnthis; } publicPersionprintPhoneNumber(){ System.out.println(this.phoneNumber); returnthis; } publicPersionprintAddress(){ System.out.println(this.address); returnthis; } }
Test.java:
publicclassTest{
publicstaticvoidmain(String[]args){
Persionpersion1=newPersion();
persion1.setId(3).setName("John")
.setPhoneNumber("1111111").setAddress("US");
persion1.printId()
.printName()
.printPhoneNumber()
.printAddress();
}
}
链式方法,就是在除最后一个方法外,每个方法都返回一个对象或者调用同一个对象的多个方法。这种编程方式:编程性强;可读性强;代码简洁。但是不易于调试。