javascript方法的鏈式調用

function $(){
	var elements = [];
	for(var i = 0,len = arguments.length; i < len; i++){
		var element = arguments[i];
		if(typeof element === 'string'){
			element = document.getElementById(element);
		}
		if(arguments.length === 1){
			return arguments;
		}
		elements.push(element);
	}
	return elements;
}
//把$函數改成工廠方法

;(function(){
	_$ = function(els){
		this.elements = [];
		for(var i = 0,len = els.length; i < len; ++i){
			var element = arguments[i];
			if(typeof element === 'string'){
				element = document.getElementById(element);
			}
			this.elements.push(element);
		}
	}
	window.$ = function(){
		return new _$(arguments);
	}
})();

;(function(){
	function _$(){
		console.log("init...");
	}
	_$.prototype = {
		each : function(){
			console.log("each...");
			return this;
		},
		setStyle : function(){
			console.log("setStyle...");
			return this;
		}
	}
	window.$ = function(){
		return new _$(arguments);
	}
})();


Function.prototype.method = function(name, fn){
	this.prototype[name] = fn;
	return this;
};
(function(){
	function _$(els){
		
	}
	_$.method('addEvent',function(){
		console.log("addEvent");
	}).method('addClass',function(){
		console.log("addClass");
	})
	
	window.$ = function(){
		return new _$(arguments);
	}
})();

//添加一個安裝器
Function.prototype.method = function(name, fn){
	this.prototype[name] = fn;
	return this;
};
(function(){
	function _$(){
		
	}
	_$.method('show',function(type, fn){
		console.log("show...");
	});

	window.installHelper = function(scope, interface){
		scope[interface] = function(){
			return new _$(arguments);
		}
	};
})();

window.addEventListener("DOMContentLoaded",function(){
	//$("topic");
	//$("topic");
	//$("topic").addEvent(); 
	//installHelper(window, '$');
	//$("topic").show() 

	//定義命名空間
	window.com = window.com || {};
	com.example = com.example || {};
	com.example.util = com.example.util || {};

	installHelper(com.example.util,'get');

	;(function(){
		var get = com.example.util.get;
		get('topic').show();     
	})();

},false);
在javascript中對象是作爲引用被傳遞的,讓一個類的每個方法都return this
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章