1、只调用一次函数

  1. function once(fn) {
  2. let done = false
  3. return function () {
  4. if (!done) {
  5. done = true
  6. return fn.apply(this, arguments)
  7. }
  8. }
  9. }
  10. let pay = once(function (money) {
  11. console.log('money', money)
  12. })
  13. pay(5)
  14. pay(4)

2、函数缓存

  1. function getArea(r) {
  2. console.log('执行area')
  3. return Math.PI * r * r
  4. }
  5. function memoize(f) {
  6. let catche = {}
  7. return function () {
  8. let key = JSON.stringify(arguments)
  9. catche[key] = catche[key] || f.apply(f, arguments)
  10. return catche[key]
  11. }
  12. }
  13. let getAreaWithMemoize = memoize(getArea)
  14. console.log(getAreaWithMemoize(4))
  15. console.log(getAreaWithMemoize(4))
  16. console.log(getAreaWithMemoize(4))