JavaScript中链式调用之研习 -- 修改

2011-08-23 16:00:42 by 【6yang】, 118 visits, 收藏 | 返回

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript中链式调用之研习 -- 修改</title>
</head>

<body>
<script>
/**
 * chain 精简版
 * @param {Object} obj
 */
function chain(obj){
    var fun = function(){
        if (arguments.length == 0){               
            return obj;
        }
        var methodName = arguments[0], methodArgs = [].slice.call(arguments,1);
        obj[methodName].apply(obj,methodArgs);
        return fun;
    }   
    return fun;
}
//定义的function/类ClassB
function ClassB(){
    this.prop1 = null;
    this.prop2 = null;
    this.prop3 = null;
}
ClassB.prototype = {
    method1 : function(p1){
        this.prop1 = p1;
    },
    method2 : function(p2){
        this.prop2 = p2;
    },
    method3 : function(p3){
        this.prop3 = p3;
    }
}

var obj = new ClassB();
chain(obj)('method1',4)('method2',5)('method3',6)(); // obj -> prop1=4,prop2=5,prop3=6
 
alert(obj.prop2);

</script>
</body>
</html>

分享到:
share

    图片原图

    loading

    loading