思路:链式调用是返回_()构造的原型对象,将新增的方法,绑定在生成的原型对象上(mixin)。
_.chain([1,2,3,4,5,2,3,4,5,'a', 'A']).uniq(function(val){
return typeof val === "string"? val.toLocaleLowerCase(): val;
})
function(root) {
var _ = function(obj){
if (!(this instanceof _)) {
return new _(obj);
}
this.wrap = obj;
}
_.uniq = function(target, callback) {
var result = [];
var computed;
for (var i=0; i<target.length; i++) {
computed = callback? callback(target[i]): target[i];
if (result.indexOf(computed) == -1) {
result.push(computed);
}
}
return result;
}
_.reduce = function(){
}
// 链式调用
_.chain = function(obj){
var instance = _(obj);
instance._chain = true;
return instance;
}
// 终结链式调用
_.prototype.value = function(){
return this.wrap;
}
// 辅助函数 是实例对象
_.result = function(instance, obj){
return instance._chain? _(obj).chain(): obj;
}
_.each = function(arr, callback) {
for (var i=0; i<arr.length; i++) {
callback.call(arr, arr[i])
}
}
_.functions = function(obj) {
var result = [];
for (var key in obj) {
result.push(key);
}
return result;
}
_.mixin = function(obj){
_.each(_.functions(obj), function(key){
var func = obj[key];
obj.prototype[key] = function(){
var args = [this.wrap];
Array.prototype.push.apply(args, arguments);
return _.result(this, func.apply(this, args));
}
})
}
_.mixin(_);
root._ = _;
}(this)
网友评论