什么是闭包?

Douglas Crockford 在 《JavaScript:The Good Parts》中说:一个内部函数除了可以访问自己的参数和变量,同时它也能自由访问把它嵌套在其中的父函数的参数和变量。

简单来说:闭包就是携带状态的函数,并且它的状态可以完全对外隐藏起来。

curry

curry: 只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数

  1. function curry(func) {
  2. const len = func.length
  3. function judgeCurry() {
  4. const arg = arguments
  5. if (arguments.length >= len) {
  6. return func.apply(null, arg)
  7. } else {
  8. return function() {
  9. return judgeCurry.call(null, ...arg, ...arguments)
  10. }
  11. }
  12. }
  13. return judgeCurry
  14. }
  15. // 测试
  16. const add = (a, b, c) => a + b + c
  17. const curryAdd = curry(add)
  18. console.log(curryAdd(1)(2)(3))
  19. console.log(curryAdd(1)(2,3))
  20. console.log(curryAdd(1,2,3))

compose

  1. const compose = function() {
  2. const len = arguments.length
  3. const args = [].slice.call(arguments)
  4. return function() {
  5. const initValue = args[len - 1].apply(null, arguments)
  6. const remainFunctions = args.slice(0, len - 1).reverse()
  7. return remainFunctions.reduce(function(previousValue, currentValue) {
  8. return currentValue(previousValue)
  9. }, initValue)
  10. }
  11. }
  12. // 测试
  13. const display = x => console.log(x)
  14. const toUpperCase = x => x.toUpperCase()
  15. const addPrefix = x => `prefix_${x}`
  16. const addSuffix = x => `${x}_suffix`
  17. const fixWord = compose(display, addPrefix, addSuffix, toUpperCase)
  18. fixWord('hello world')

memo

  1. function memo(func) {
  2. const memoize = function(key) {
  3. const cache = memoize.cache
  4. console.log(cache.hasOwnProperty(key))
  5. if (!cache.hasOwnProperty(key)) {
  6. cache[key] = func.apply(null, arguments)
  7. }
  8. return cache[key]
  9. }
  10. // 绑定到闭包函数上,不会造成内存泄露
  11. memoize.cache = {}
  12. return memoize
  13. }
  14. // 测试
  15. const fibonacci = n => {
  16. if (n === 1 || n === 2) {
  17. return 1
  18. } else {
  19. return fibonacci(n - 1) + fibonacci(n - 2)
  20. }
  21. }
  22. const memoFibonacci = memo(fibonacci)
  23. console.log(memoFibonacci(10))
  24. console.log(memoFibonacci(10))

文章写于2019年11月