我是靠谱客的博主 舒心百合,这篇文章主要介绍源码分析,现在分享给大家,希望可以做个参考。

一、call和apply
myCall实现call效果

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
Function.prototype.myCall=function(){ var ctx=arguments[0]||window; ctx.fn=this; var args=[]; var len=arguments.length; for(var i=1;i<len;i++){ args.push('arguments['+i+']'); } var result=eval('ctx.fn('+args.join(',')+')'); return result; }

myApply实现apply效果

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Function.prototype.myApply = function (ctx, arr) { ctx = ctx || window; ctx.fn = this; var result; if (arr) { var args = []; for (var i = 0; i < arr.length; i++) { args.push('arr[' + i + ']'); } result = eval('ctx.fn(' + args.join(',') + ')'); } else { result = ctx.fn(); } delete ctx.fn; return result; }

二、map和 reduce
selfMap实现map效果

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.prototype.selfMap = function () { const ary = this const result = [] const [ fn, thisArg ] = [].slice.call(arguments) if (typeof fn !== 'function') { throw new TypeError(fn + 'is not a function') } for (let i = 0; i < ary.length; i++) { result.push(fn.call(this, ary[i])) } return result } const a = new Array(1, 2, 3, 4,5); console.log(a.selfMap(item => item *2));

selfReduce实现reduce效果

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Array.prototype.selfReduce= function (fn,init) { var len=this.length; var pre=init; var i=0; if(init==undefined){ pre=this[0]; i=1; } for(i;i<len;i++){ pre=fn.call(pre,this[i]); } return pre; } const b = new Array(1, 2, 3, 4,5); console.log(b.selfReduce((preTotal,ele)=>preTotal+ele));

三、reduce实现map和filter
reduce实现map

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const reduceMap=(fn,thisArg)=>{ return (list)=>{ if(typeof fn!=="function"){ throw new TypeError(fn+'is not a function'); } if(!Array.isArray(list)){ throw new TypeError('list not be a Array'); } if(list.length==0) return [] return list.reduce((acc,value,index)=>{ return acc.concat([fn.call(thisArg,value,index,list)]) },[]) } } console.log(reduceMap(x=>x+1)([1,2,3]))

reduce实现filter

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const reduceFilter=(fn,thisArg)=>{ return (list)=>{ if(typeof fn!=="function"){ throw new TypeError(fn+'is not a function'); } if(!Array.isArray(list)){ throw new TypeError('list not be a Array'); } if(list.length==0) return [] return list.reduce((acc,value,index)=>{ return fn.call(thisArg,value,index,list)?acc.concat([value]):acc },[]) } } console.log(reduceFilter(x=>x%2===0)([1,2,3]))

文章参考:https://juejin.im/post/5c0b7f03e51d452eec725729

最后

以上就是舒心百合最近收集整理的关于源码分析的全部内容,更多相关源码分析内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部