转http://bbs.blueidea.com/thread-2942014-1-1.html
另外还可以看看javascript设计模式的第6章
用过jQuery的朋友一定对jQuery中方法的链式调用印象深刻,最近发布的YUI3也支持了方法的链式调用。这是一个非常不错的语法特性,能让代码 更加简洁、易读。很多时候链式调用可以避免多次重复使用一个对象变量,从而减少代码,而js是一种客户端执行的脚本语言,减少代码就减少了js文件的大 小,减少了服务器的压力。链式调用这么多优点,它是如何实现的呢?这篇文章就是想探讨一下这个问题。
append: function() {
return this.domManip(arguments, true, function(elem){
if (this.nodeType == 1)
this.appendChild( elem );
});
}
function Dog(name,color){
this.name=name||"";
this.color=color||"";
}
Dog.prototype.setName=function(name){
this.name=name;
return this;
};
Dog.prototype.setColor(color){
this.color=color;
return this;
};
Dog.prototype.yelp(){
alert("我的名字叫:"+this.name+",我的颜色是:"+this.color);
return this;
};
var dog = new Dog();
dog.setName("旺财").setColor("白色").yelp();
Dog.prototype.getName(callback){
callback.call(this,this.name);
return this;
}
function showName(name){
alert(name);
}
dog.setName("旺财").getName(showName).setColor("白色");