bind、apply、call的实现,常用函数的实现

1.call的实现

1 Function.prototype.mycall = function (context) {
2   context.fn = this
3   const args = [...arguments].slice(1)
4   const result = context.fn(...args)
5   delete context.fn
6   return result
7 }

2.appyl的实现

1 Function.prototype.myapply = function (context) {
2   context.fn = this
3   const args = arguments[1] ? arguments[1] : []
4   const result = context.fn(...args)
5   delete context.fn
6   return result
7 }

3.bind的实现

1 Function.prototype.mybind = function (context) {
2   const self = this
3   const args1 = [...arguments].slice(1)
4   return function () {
5     const args2 = [...arguments]7     return self.apply(context, [...args1, ...args2])
8   }
9 }

 4.reduce的实现

 1 Array.prototype.myreduce = function (fn, initValue) {
 2   const array = this
 3   if (array.length === 0) {
 4     if (initValue === undefined) throw '传参错误'
 5     else return initValue
 6   }
 7   let result = initValue ? initValue : array[0]
 8   let startIndex = initValue ? 0 : 1
 9   for (let i = startIndex; i < array.length; i++) {
10     result = fn(result, array[i])
11   }
12   return result
13 }        

 5.防抖函数

 1 /**
 2  * 防抖函数
 3  * @param {*} fn 函数
 4  * @param {*} delay 延迟时间ms
 5  * @returns 
 6  */
 7 function debounce(fn, delay) {
 8   let timer = null
 9   return function() {
10     if (timer) clearTimeout(timer)
11     timer = setTimeout(() => {
12       fn.apply(this, arguments)
13     }, delay)
14   }
15 }

6.节流函数

 1 /**
 2  * 节流函数
 3  * @param {*} fn 
 4  * @param {*} delay 
 5  * @returns 
 6  */
 7 function throttle(fn, delay) {
 8   let prevtime = 0
 9   return function () {
10     const now = new Date().getTime()
11     if (now - prevtime > delay) {
12       fn.apply(this, arguments)
13       prevtime = now
14     }
15   }
16 }

 

posted @ 2021-03-29 16:16  jianghongyun  阅读(72)  评论(0)    收藏  举报