日期:2014-05-16  浏览次数:20381 次

几种方式实现JS链式操作。

jQuery太大了,觉得挺实用的,但是我水平很菜,用不到那么多的功能,只需要用几个简单的功能:设置样式,设置属性,添加元素。一直没有时间做,这次利用制作项目的机会,顺便写出来了。

做了一个简单的DOM对象的包装,增加了几个简单的方法,常用的。类似jQuery的链式操作。

没做错误处理。方法:attr,append,appendTo,html,css。

$c创建对象之后,就可以使用这些方法。

?

function extend(obj){
	    (function(){
		    this.append=function(obj){
			    this.appendChild(obj);
			    return this;
		    }
            this.appendTo=function(obj){
			    obj.appendChild(this);
			    return this;
		    }
            this.attr=function(a,b){
			    if(a instanceof Object){
				    for(var x in a){
					    this.setAttribute(x,a[x]);
				    }
			    }else{
				    this.setAttribute(a,b);
			    }
			    return this;
		    }
		    this.css=function(a,b){
			    if(a instanceof Object){
				    for(var x in a){
					    this.style[x]=a[x];
				    }
			    }else{
				    this.style[a]=b;
			    }
			    return this;
		    }
            this.html=function(str){
				if( typeof str =='undefined')return this.innerHTML;
			    this.innerHTML=str;
			    return this;
		    }
	    }).apply(obj);
        return obj;
    }

    function $c(str){return extend(document.createElement(str));}
?

?

使用时可以对某个html对象使用extend方法。然后该对象就可以进行链式操作。

实现的思路是通过apply 用 要包装的对象替换了函数中的this对象。使得该对象拥有了那些this写的方法。

?

今天看了别人实现的JS链式操作,感觉更精炼一些。(来自JSMIX )

?

(function(){
	function _$(id){
		this.ele = document.getElementById(id);
	}
	_$.prototype = {
		setColor : function(c){
			this.ele.style.color = c;
			return this;  // Important
		},
		setBold : function(){
			this.ele.style.fontWeight = "bold";
			return this;  // Important
 
		}
		/** 更多方法 **/
	}
	window.$ = function(id){
		return new _$(id);
	}
})();
?

通过 prototype关键字 修改对象原型 来实现链式操作。prototype和apply经常被用来作比较,比如模仿继承特性。不过我不喜欢prototype。。。害怕出现别的问题。