2022-4-5-深拷贝函数

function deepCopy(src) {
    let result = Array.isArray(src) ? [] : {}
    for(let key in src) {
        if(typeof src[key] === 'object' && src[key] !== null) {
            console.log('1')
            result[key] = deepCopy(src[key])
        }else {
            console.log("2")
            result[key] = src[key]
        }
        
    }
    return result
}
let o = { a: [1,{ key:'value' }], c:{ name:'4399' } }
let m = deepCopy(o)
console.log(m)
console.log(m.a === o.a, m.c === o.c, m.a[1] === o.a[1])    // false false false
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

2022-4-5-节流函数

const $html = document.documentElement
$html.onscroll = e => myThrottle((e)=>{})
function myThrottle(fn, interval=300) {
    let canRun = true
    return function() {
        if(!canRun) {
            // 被节流
            return
        }

        canRun = false
        setTimeout(()=>{
            fn.apply(this, arguments)
        }, interval)
    }
}
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

2022-4-5-防抖函数

const $input = document.querySelector('input')
$input.onclick = (e) => myDebounce(({ target }) => {})
function myDebounce(fn, interval=300) {
    let timer = null
    return function() {
        timer = setTimeout(()=>{
            clearTimeout(timer)
            fn.apply(this, arguments)
        }, interval)
    }
}
复制成功
1
2
3
4
5
6
7
8
9
10
11

2022-4-6-JS继承

function Parent() {
  constructor() {}
  this.color = 'red'
  this.say = ()=>{}
}
Parent.prototype.introduce = ()=>{}
function Child() {
  //继承属性
  Parent.apply(this, arguments)
}
function inheritPrototype(pa, ch) {
  const prototype = Object.create(pa.prototype)
  prototype.constructor = ch
  ch.prototype = prototype
}
//继承原型
inheritPrototype(Parent, Child)
//书写自己的原型
Child.prototype.announce = ()=>{}
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Hook

2022-4-8-写一个本地存储的自定义hook

参考useHooks实现,这个Hook其实是useDarkTheme的组成之一。

(value是基本数据类型,对象,数组,useHook实现考虑了value是function的情况)

// Usage
function App(props) {
    // P.S. Hook需要在顶层使用
    const [name, setName] = useLocalStorage("name", "Bob")
    
	return <input onChange={e => setName(e.target.value)}>{ name }</input>
}
// Hook
function useLocalStorage(key, initialValue) {
	// 1.State to store our value
  	// Pass initial state function to useState so logic is only executed once
    const [storedValue, setStoredValue] = useState(()=>{
        if(!window.localStorage) return initialValue
        
        try {
            const item = localStorage.getItem(key)
        	return item ? JSON.parse(item) : initialValue
        }catch {
            return initialValue
        }
    })
    
    //	2.Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
    const setValue = (key, value) => {
        try {
             // Save state
            setStoredValue(key, value)
     		// Save to local storage
         	window.localStorage.setItem(key, JSON.stringify(value))
        }catch(err) {
            console.log(err)
        }
    }
    
    // 自定义hook最后返回的成员
    return [storedValue, setValue]
}
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

2022-4-8-抽离轮询逻辑 hook

// Usage
import react from 'react'
import { useInterval } from './useInterval.js'

function App(props) {

    const fetchData = async () => {
        // const data = await ClientService.getallregionsumtoday()
        if (!data) return
  	}
    useInterval(fetchData, 5000)
    return <>{source.map(q=>q.name)}</>
}

// Hook
import { useRef, useEffect } from 'react'

export function useInterval(callback, delay) {
  const savedCallback = useRef()

  // 保存新回调
  useEffect(() => {
    savedCallback.current = callback
  })

  // 建立 interval
  useEffect(() => {
    function tick() {
      savedCallback.current()
    }
    if (delay !== null) {
      let id = setInterval(tick, delay)
      return () => clearInterval(id)
    }
  }, [delay])
}
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
晓露寝安浅云逍遥十漾轻拟