javascriptメソッドのチェーン呼び出し
2264 ワード
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とする.