js部分:
/**
* 简易的链式调用框架
* 要点:1.框架主体以函数式编程为核心 2.辅以构造函数原型链实现链式调用
* 注意:在链式调用过程中,始终有一个值是从传入,到最后终止链式时,一直变化,在此例中这个值就为this.wrap,其伴随整个过程
*/
;(function(root) {
var push = Array.prototype.push
var _ = function(wrap) {
if (!(this instanceof _)) {
return new _(wrap)
}
this.wrap = wrap
}
_.chain = function(obj) {
var instance = _(obj)
instance._chain = true
return instance
}
_.val = function() {
this._chain = false
return this.wrap
}
var result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj
}
_.uniq = function(arr, callback) {
let temp = []
for(var i = 0; i < arr.length; i++) {
var cur = callback ? callback(arr[i]) : arr[i]
if (temp.indexOf(cur) === -1) {
temp.push(cur)
}
}
return temp
}
_.map = function() {
console.log(1)
}
_.each = function(arr, callback) {
for(var i = 0; i < arr.length; i++) {
callback.call(arr[i], arr[i])
}
}
_.functions = function(obj) {
var keyNameAry = []
for(var i in obj) {
keyNameAry.push(i)
}
return keyNameAry
}
_.mixin = function(underscore) {
_.each(_.functions(underscore), function(keyName) {
var func = underscore[keyName]
_.prototype[keyName] = function() {
var args = [this.wrap]
push.apply(args, arguments)
return result(this, func.apply(this, args))
}
})
}
_.mixin(_)
root._ = _
})(this)
html:
<!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>
</head>
<body>
<script src="./underscore.js"></script>
<script>
var arr = [1,1,2,2,3,4,5,5,6,'a','A','b','B','c']
// var result1 = _.uniq(arr, function(val) {
// return typeof val === 'string' ? val.toLowerCase() : val
// })
// console.log(result1, 'result1')
// var result2 = _().uniq(arr)
// console.log(result2, 'result2')
var result3 = _(arr).chain().uniq(function(val) {
return typeof val === 'string' ? val.toLowerCase() : val
}).val()
console.log(result3, arr, 'result3')
</script>
</body>
</html>