【问题标题】:How the "arguments" is passed through the debounce functions?“参数”如何通过 debounce 函数传递?
【发布时间】:2019-12-18 16:27:40
【问题描述】:

我刚刚看到这个关于去抖动的教程,但是当他使用debounceSayHello("Jeremy") 时,我对如何在去抖动中通过所有这些函数传递名称参数感到非常困惑。为什么debounce(sayHello,3000) 而不是debounce(()=>sayHello(name),3000)?而当定义内部返回的匿名函数时,那里没有参数,'Jeremy'是如何传入并最终到达apply函数的?非常感谢!

function debounce (func, delay) {
  let timerId;
  return function () {
    if (timerId) {
      clearTimeout(timerId)
    }
    timerId=setTimeout(()=>func.apply(this,[...arguments]),delay);
  }
}

function sayHello(name){
 console.log(`Hello ${name}`);
}

let debouncedSayHello=debounce(sayHello,3000);

debouncedSayHello('Jeremy')





//Hello Jeremy

原文:

【问题讨论】:

  • sayHello(name) 会立即调用该函数并执行它并发送该方法返回的内容。

标签: javascript this apply bind debounce


【解决方案1】:

Arguments 是一个可在函数内部访问的类数组对象,其中包含传递给该函数的参数值。

 function sumTotal(){
      console.log(arguments); // {'1':1,'2':2,'3':3,'4': 4}
      var numSet = [...arguments];
      return numSet.reduce((total, num)=>total+num);
    }

 console.log('Sum: ', sumTotal(1,2,3,4));//Sum: 10

【讨论】:

  • 啊,非常感谢!所以当我们定义一个函数时,比如“function sumTotal()”,即使我们没有像“function sumTotal(num1, num2) {}”那样定义它,当我们用参数调用函数时,如果我们在里面使用“arguments”它仍然适用于我们传入的所有参数,对吗?非常感谢!那么对于 debounce 函数,是否正确:当我们使用 debounce('sayHello',3000) 时,我们实际上存储了返回的函数 "function() {if(timeId....) timeId=...func.apply (this,[...arguments])}" 到 debounceSayHello,然后我们实际上用 'Jeremy' 调用了返回的函数..
  • 即使它没有用参数定义,我们的 'Jeremy' 也会转到 [...arguments] ,所以我们可以使用 apply 来调用带有这个 'Jeremy' 的 SayHello 对吗?非常感谢!!!:D
  • 参数是函数内部的特殊对象,它将传递给函数的参数存储在其中。
猜你喜欢
  • 2018-08-05
  • 2021-10-18
  • 1970-01-01
  • 2020-03-25
  • 2010-09-13
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2021-04-24
相关资源
最近更新 更多