闭包中 func.apply(this, args) 和 func(...args) 的区别

问题描述 投票:0回答:1

我在尝试理解使用闭包的一些概念时遇到了以下事情。 当我阅读有关记忆/节流的内容时,人们在闭包中使用

func.apply(this, args)

以下是来自 2 个不同来源的一些示例:

function memoize(func) {
  const cache = {}
  return function(...args) {
    const key = JSON.stringify(args)
    if (cache[key]) {
      return cache[key]
    } else {
      const result = func.apply(this, args) // (*)
      cache[key] = result
      return result
    }
  }
}

function throttle(func, interval) {
  let isRunning = false;

  return function (...args) {
    if (!isRunning) {
      isRunning = true;
      func.apply(this, args); // (*)

      setTimeout(() => {
        isRunning = false;
      }, interval);
    }
  };
}

所以我的问题是:我们可以用

func(...args)
代替吗?如果我们使用扩展运算符调用
func
而不是
apply
,实际区别是什么?

javascript closures this
1个回答
0
投票

如果您使用

func(...args)
,则不会为
this
设置
func
值,其值将取决于您是否处于严格模式。

© www.soinside.com 2019 - 2024. All rights reserved.