您的位置:首页 > Web前端 > JavaScript

javascript实现简单的链式调用

2012-08-21 00:00 537 查看
用过jQuery的朋友一定对jQuery中方法的链式调用印象深刻,貌似现在很多库都支持了方法的链式调用,比如YUI3等。链式调用是一个非常不错的语法特性,能让代码更加简洁、易读。很多时候链式调用可以避免多次重复使用一个对象变量。今天有人在群里说起javascript链式调用,写了几个简单的实现方式共大家参考一下:
一般我们我用函数构造一个类,例如:

viewsource

print
?

01varfunctionDog(name,age){
02this.name=name;
03this.age=age;
04};
05Dog.prototype={
06getName:function(){
07console.log(this.name);
08},
09getAge:function(){
10console.log(this.age);
11}
12};
定义一个Dog类,并具备几个简单的方法

viewsource

print
?

1vardog1=newDog("旺旺",3);
2dog1.getName();
3dog1.getAge();
实例化,并且调用方法。

要实现链式调用是非常简单的事情,唯一需要做的就是在每个方法后面返回this。例如:

viewsource

print
?

01varDog=function(name,age){
02this.name=name;
03this.age=age;
04};
05Dog.prototype={
06getName:function(){
07console.log(this.name);
08returnthis;
09},
10getAge:function(){
11console.log(this.age);
12returnthis;
13}
14};
15
16vardog1=newDog("旺旺",3);
17dog1.getName().getAge();
上面的代码可以看出,Dog方法上多了一段代码:returnthis;
细心一点你会发现这里dog1实例前还需要一个new初始化,还是有点不方便。在改进一下:

viewsource

print
?

01varDog=function(name,age){
02this.name=name;
03this.age=age;
04};
05Dog.prototype={
06getName:function(){
07console.log(this.name);
08returnthis;
09},
10getAge:function(){
11console.log(this.age);
12returnthis;
13}
14};
15window.Dogs=function(name,age){
16returnnewDog(name,age);
17};
18Dogs("旺旺",3).getName().getAge();
这里在window下定义一个Dogs方法,作为Dog的别名,这样就可以直接用Dogs(“旺旺”,3).getName().getAge();这样调用了。
苛刻的网友说这样太暴露了,这样有两个全局变量变量Dog和Dogs,在改进一下:

viewsource

print
?

01varDog=function(name,age){
02if(!(thisinstanceofDog)){
03returnnewDog(name,age);
04}
05this.name=name;
06this.age=age;
07};
08Dog.prototype={
09getName:function(){
10console.log(this.name);
11returnthis;
12},
13getAge:function(){
14console.log(this.age);
15returnthis;
16}
17};
18Dog("旺旺",3).getName().getAge();
这里在构造函数中加了这么一句:

viewsource

print
?

1if(!(thisinstanceofDog)){
2returnnewDog(name,age);
3}
判断this是否为Dog实例,如果不是就创建一个新实例。

更为安全代码:

viewsource

print
?

01(function(){
02varDog=function(name,age){
03if(!(thisinstanceofDog)){
04returnnewDog(name,age);
05}
06this.name=name;
07this.age=age;
08};
09Dog.prototype={
10getName:function(){
11console.log(this.name);
12returnthis;
13},
14getAge:function(){
15console.log(this.age);
16returnthis;
17}
18};
19return(window.Dog=Dog);
20})();
21Dog("旺旺",3).getName().getAge();
或者:

viewsource

print
?

01(function(){
02varDog=function(name,age){
03this.name=name;
04this.age=age;
05};
06Dog.prototype={
07getName:function(){
08console.log(this.name);
09returnthis;
10},
11getAge:function(){
12console.log(this.age);
13returnthis;
14}
15};
16window.Dogs=function(name,age){
17returnnewDog(name,age);
18};
19})();
20
21Dogs("旺旺",3).getName().getAge();
希望对新手有所帮助,如有不对之处欢迎留言拍砖斧正!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链式调用