一些没啥卵用js功能函数的笔记

 1 //防抖 经过一定的延迟执行一次 接受一个函数 返回防抖的函数
 2 function debounce(fn,delay){
 3 
 4     var _args = Array.prototype.slice.call(arguments,2) //获取参入的参数
 5     var timer = null;
 6     return function(){
 7         var that = this //保存this对象 因为有些事件触发需要保存当前的对象
 8         var _secondArgs = [].concat(Array.prototype.slice.call(arguments),_args) //获取参入的参数
 9         clearTimeout(timer);
10         timer = setTimeout(function(){
11             fn.apply(that,_secondArgs)
12         },delay)    
13     }
14 }
15 
16 var test = document.getElementById('test')
17 var hello = '456'
18 test.name = '123'
19 var hh = throttle(function(){
20     console.log(this.name,hello)
21 },2000,hello)
22 
23 test.onclick = hh
24 
25 
26 //节流
27 function throttle(fn,delay){
28     var _args = Array.prototype.slice.call(arguments,2) //获取参入的参数
29     var timer = null;
30     return function(){
31         var that = this //保存this对象 因为有些事件触发需要保存当前的对象
32         var _secondArgs = [].concat(Array.prototype.slice.call(arguments),_args) //获取参入的参数
33         if(!timer){
34             timer = setTimeout(function(){
35                 fn.apply(that,_secondArgs);
36                 timer = null
37             },delay)    
38         }
39         
40     }
41 }
42 
43 //var a = b.bind()
44 //bind的模拟实现
45 Function.prototype.bind1 = function(context){
46     var that = context
47     var self = this
48     var _args = Array.prototype.slice.call(arguments,1);
49     
50     var fund = function(){
51         //这个函数会返回出去 如果作为构造函数使用的话 这个函数内部的this就是指向实例
52         var args = _args.concat([].slice.call(arguments));
53         //如果作为构造函数调用 -- 判断依据 返回函数是不是实例的构造函数
54         if(this instanceof fund){
55             //是的话 重新绑定this
56             return self.apply(this,args)
57         }else{
58             return sele.apply(that,args)
59         }
60   
61     }
62         //设置原型
63         fund.prototype = self.prototype
64         return fund
65       
66 }
67 
68 //数组扁平化
69 function flattern(array){
70     var _returnArray = []
71     array.forEach(function(ele){
72         if(Array.isArray(ele)){
73             //还是数组的话继续递归
74             _returnArray = _returnArray.concat(flattern(ele))
75         }else{
76             _returnArray.push(ele)
77         }
78     })
79 
80     return _returnArray
81     
82 }
83 
84 console.log(flattern([1,2,[3,4,[5,6,7]],[8,9,[10,[11,12[13,14]]]]]))

猜你喜欢

转载自www.cnblogs.com/carrotWu/p/9071388.html
今日推荐