underscore两个使用方式:
- 调用静态方法;
- 调用实例方法;
_.unique([1,2,5,6,3,4,5,6,1,2,'A','a'], function(item){
return typeof item === 'string' ? item.toLocaleLowerCase() : item;
}));
_([1,2,5,6,3,4,5,6,1,2,'A','a']).chain().unique(function(item){
return typeof item === 'string' ? item.toLocaleLowerCase() : item;
}).value();
(function(root){
// 构造函数
var _ = function(obj) {
if (!(this instanceof _)){
return new _(obj);
}
this.wrap = obj;
};
_.map = function(arg1, arg2, arg3) {
//console.log(1)
}
// 开启链式调用
_.chain = function(obj){
//特殊的实例对象
var instance = _(obj);
instance._chain = true;
return instance;
}
var result = function(instance, obj) {
if (instance._chain){
instance.wrap = obj;
return instance;
}
return obj;
};
_.max = function(args){
args.push('haha');
return args;
}
_.unique = function(array, callback){
var result = [];
for(var i=0; i < array.length; i++) {
var item = callback ? callback(array[i]) : array[i];
if(result.indexOf(item) === -1) {
result.push(item);
}
}
return result;
}
_.each = function(array, callback){
for(var i=0; i < array.length; i++) {
callback.call(array, array[i]);
}
}
_.functions = function(obj){
var result = [];
for(var key in obj){
result.push(key);
}
return result;
}
_.prototype.value = function(){
return this.wrap;
}
_.mixin = function(obj) {
_.each(_.functions(obj), function(key){
var func = obj[key];
_.prototype[key] = function(){
var args = [this.wrap];
// 数组合并
Array.prototype.push.apply(args, arguments);
// 判断是否是链式调用 this._chain === true
// 数据经过某个工序处理之后的结果
return result(this, func.apply(this, args));
};
});
}
_.mixin(_);
root._ = _;
})(this);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./underscore.js"></script>
</head>
<body>
<script>
// underscore 的两种调用方式
// 1. underscore的静态方法调用
console.log(_.unique([1,2,5,6,3,4,5,6,1,2,'A','a'], function(item){
return typeof item === 'string' ? item.toLocaleLowerCase() : item;
}));
// 2. underscore示例方法的调用
var data = _([1,2,5,6,3,4,5,6,1,2,'A','a']).chain().unique(function(item){
return typeof item === 'string' ? item.toLocaleLowerCase() : item;
}).value();
console.log(data);
</script>
</body>
</html>