---
title: "javascript链式调用的设计"
author: "karrykai"
date: "2009-07-29T22:19:31Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2009-09-22T17:22:47Z"
id: 474386
url: "https://karrykai.iteye.com/blog/474386"
---

用过jQuery的朋友一定对jQuery中方法的链式调用印象深刻，最近发布的YUI3也支持了方法的链式调用。这是一个非常不错的语法特性，能让代码更加简洁、易读。很多时候链式调用可以避免多次重复使用一个对象变量，从而减少代码，而js是一种客户端执行的脚本语言，减少代码就减少了js文件的大小，减少了服务器的压力。链式调用这么多优点，它是如何实现的呢？这篇文章就是想探讨一下这个问题。

链式调用例子如：$("p").append("test").fadeIn("fast");

看一段jQuery的源码：

append: function() {  
        return this.domManip(arguments, true, function(elem){  
            if (this.nodeType == 1)  
                this.appendChild( elem );  
        });  
    }

以上是jQuery中append方法的实现。append方法是向每个匹配的元素内部追加内容的方法，很明显，属于赋值操作，但是却有**返回值**，返回的是当前操作的dom(通常返回this指针)。这是链式调用的关键，你会发现这不过是个**语法小技巧**而已。

很明显，在赋值器方法中(或者本身没有返回值的方法中)很容易实现链式调用，而取值器相对来说不好实现链式调用，因为你需要取值器返回你需要的数据而不是this指针(当然，如果你坚持要实现链式方法，也可以用回调函数来实现)。

**设计一个简单的支持链式调用的类：**

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();

**取值器你也想支持链式调用？**  
那就用回调函数来实现，将本来应该返回的值直接传给回调函数，而return仍然返回this指针。接着上面的Dog类写一个方法：

Dog.prototype.getName(callback){  
        callback.call(this,this.name);  
        return this;  
}

使用方式：

function showName(name){  
        alert(name);  
}  
dog.setName("旺财").**getName(showName)**.setColor("白色");

Copyright [playgoogle.com](http://www.playgoogle.com)© 2008

[继续阅读《javascript链式调用的设计》的全文内容...](http://www.playgoogle.com/post/94.html)

### 相关文章:

- [javascript中的memoization(memoizing) 技术介绍](http://www.playgoogle.com/post/96.html)  (2009-8-5 19:22:19)
  
  [onbeforeunload与a标签在IE中的冲突](http://www.playgoogle.com/post/92.html)  (2009-7-25 14:57:51)
  
  [基于jQuery UI的图片截取(圈人)功能](http://www.playgoogle.com/post/91.html)  (2009-7-21 15:0:11)
  
  [整理：详解javascript function中的caller,callee,call,apply](http://www.playgoogle.com/post/90.html)  (2009-7-4 11:41:33)
  
  [jQuery的不足之处](http://www.playgoogle.com/post/88.html)  (2009-6-20 20:54:4)

* * *

### 最新评论:

- [2009-9-1 13:13:26](http://www.playgoogle.com/post/94.html#cmt238)，[Keeper](http://www.pinaster.net) ： 不错。这一特性很符合JS的函数式语言的特点，连续求值，函数即求值
- [2009-8-4 10:21:23](http://www.playgoogle.com/post/94.html#cmt224)，tinali ： 写的不错，学习了

![](http://www1.feedsky.com/t1/271665529/PlayGoogleKarry/feedsky/s.gif?r=http%3A%2F%2Fwww.playgoogle.com%2Fpost%2F94.html)

[![](http://www1.feedsky.com/r/i/feedsky/PlayGoogleKarry/271665529/art01.gif)](http://www1.feedsky.com/r/l/feedsky/PlayGoogleKarry/271665529/art01.html)