随手而记...
在某些有规律的对特定形式的元素或者对象操作时。wrap对于api的调用有很意想不到的作用。
简易包装:
/**
* $wrap {给一对象打包装}
* @author horizon(岑安)
*/
var $wrap = function (obj) {
//private temp object
var _obj = obj,
toString = Object.prototype.toString,
slice = Array.prototype.slice,
unshift = Array.prototype.unshift,
// define the wrpper
wrapper = function (o) { this._wrapped = o };
obj = function (o) { return new wrapper(o) }
var result = function (o, chain) { return chain ? obj(o).chain() : o; };
obj.prototype = wrapper.prototype;
for (var key in _obj) {
if (toString.call(_obj[key]) == '[object Function]') {
obj[key] = _obj[key];
wrapper.prototype[key] = (function (name, func) {
return function () {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(obj, args), this._chain);
}
})(key, _obj[key])
}
}
// define the chain, return this
wrapper.prototype.chain = function () { this._chain = true; return this; }
// define the end(), return _wrapped
wrapper.prototype.end = function () { delete this._chain; return this._wrapped }
return obj;
};
例1:
var Num = {};
Num.plus = function (a, b) { return (a + b) };
Num.substract = function (a, b) { return (a - b) };
Num.multipy = function (a, b) { return (a * b) };
Num.devide = function (a, b) { return (a / b) };
Num = $wrap(Num);
于是:
Num.plus(3, 4) // 7
Num(3).plus(4) // 7
// (3+4)*2-1
Num(3).chain()
.plus(4)
.multipy(2)
.substract(1)
.end() // 13
例2:
var dom = {};
dom.hasClass = function (ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
};
dom.addClass = function (ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
return ele;
};
dom.removeClass = function (ele,cls) {
if (this.hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
return ele;
};
dom.setStyle = function ...
dom.animate = function ...
...
dom = $wrap(dom);
// <div id="test" class="one"></div>
var el = document.getElementById('test');
dom(el).chain().
.addClass('two')
.removeClass('one')
...
.end(); // <div id="test" class="two"></div>
有局限性,适合于对同样性质的元素做类似操作时。比如 操作数组, dom元素等