# 11-05

参考:

进度:

# 原子笔记

  • 使用 new Function 创建一个函数,那么该函数的 [[Environment]] 并不指向当前的词法环境,而是指向全局环境。此类函数无法访问外部(outer)变量,只能访问全局变量。

  • 任何 setTimeoutsetInterval 都只会在当前代码执行完毕之后才会执行。

  • Spread 语法 ... 允许将 可迭代对象 args 作为列表传递给 `call``

  • ``apply仅接受 **类数组对象**args`。

  • 防抖装饰器:在“冷却(cooldown)”期后运行函数一次。适用于处理最终结果。

    function debounce(func, ms) {
      let timeout;
      return function() {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, arguments), ms);
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
  • 节流装饰器:运行函数的频率不会大于所给定的时间 ms 毫秒。适用于不应该经常进行的定期更新。

    function throttle(func, ms) {
      
      let isThrottle = false,   // 是否处于冷却时间
          savedArgs,						
          savedThis;
      
      function wrapper() {
        // 处于冷却则保存参数及 this 后返回
        if (isThrottle) {
          savedArgs = arguments;
          savedThis = this;
          return;  
        }
    	
        func.apply(this, arguments);
    	// 运行 func 后进入冷却时间
        isThrottle = true;
    	
        // ms 后解除冷却,如果存在则使用最后记忆的参数和上下文再次调用 wrapper
        setTimeout(function() {
          isThrottle = false;
          if (savedArgs) {
            // 调用 wrapper 再次执行 func 并进入冷却
            wrapper.apply(savedThis, savedArgs);
            savedArgs = savedThis = null;
          }
        }, ms);
      }
    
      return wrapper;
    }
    
    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
  • 绑定参数函数 partial

    function partial(func, ...argsBound) {
      return function(...args) {
        return func.call(this, ...argsBound, ...args);
      }
    }
    
    1
    2
    3
    4
    5
  • func.bind(context) 的结果是一个特殊的类似于函数的“外来对象(exotic object)”,没有原函数的属性。

上次更新: 11/8/2020, 2:44:59 AM