包化,集化,方法化—有关Qwrap的三个算子
[javascript]
function mul(func){
return function(){
if(arguments[0] instanceof Array){
var ret = []
for(var i=0,len = arguments[0].length;i<len;i++){
r= func.apply(null,[arguments[0][i]].concat([].slice.call(arguments,1)));
ret.push(r);
}
return ret;
}else{
return func.apply(null,arguments);
}
}
}
function methodize(func,chain){
return function(){
var ret = func.apply(null,[this.core].concat([].slice.call(arguments)));
return chain?this:ret;
}
};
function rwrap(func,wrapper,idx){
idx=idx|0;
return function(){
var ret = func.apply(this, arguments);
if(idx>=0) ret=arguments[idx];
return wrapper ? new wrapper(ret) : ret;
}
}
[/javascript]
然后我们可以这样来使用
[javascript]
function $(id){
return document.getElementById(id);
}
function getValue(el){
el.style.background = 'red';
};
function setValue(el,value){
el.innerHTML = value;
return 'hehe';
};
function w(core){
this.tt = core;
return core;
}
function test(core){
this.core = core;
};
test.prototype.set = methodize(rwrap(mul(setValue),w,0),true);
test.prototype.get = methodize(mul(getValue),true);
var ret = (new test([$('id1'),$('id2')])).get().set('-000-');
console.info( ret );
[/javascript]