在另一个函数内调用带参数的函数

时间:2017-04-06 00:40:27

标签: javascript function parameter-passing

我正在尝试构建一种调度函数,能够在随机时刻调用带有参数的另一个函数。 这是我的尝试,使用Javascript:

function scheduleFunction(t, deltaT, functionName) {

    var timeout;
    var timeoutID;

    function scheduler() {
      functionName()

      clearTimeout(timeoutID);
      timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
      timeoutID = setTimeout(scheduler, timeout);
    }

    scheduler();

  }

如果我让它调用另一个不需要参数的函数,这个函数可以正常工作。例如:

function printSomething() {
        console.log("Printing something...");
      }

scheduleFunction(1000, 500, printSomething);

不幸的是,该函数不允许使用参数调用另一个函数,例如:

function print(string) {
        console.log(string);
}

scheduleFunction(1000, 500, print("Hello World!"));

如果可能的话,我应该如何编辑调度程序函数以获得那种结果?

3 个答案:

答案 0 :(得分:4)

您可以绑定参数:

scheduleFunction(1000, 500, print.bind(null, "Hello World!"));



function scheduleFunction(t, deltaT, functionName) {
  var timeout;
  var timeoutID;

  function scheduler() {
    functionName()

    clearTimeout(timeoutID);
    timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
    timeoutID = setTimeout(scheduler, timeout);
  }

  scheduler();
}

function print(string) {
  console.log(string);
}

scheduleFunction(1000, 500, print.bind(null, "Hello World!"));




答案 1 :(得分:1)

简单

scheduleFunction(1000, 500, function() {
  print("Hello World!")
});

答案 2 :(得分:0)

当调用一个函数时,一个名为arguments的类似数组的对象变量被添加到函数作用域中。

它包含 实际传递给函数 的参数,而不仅仅是在对象定义中定义的参数。这意味着传入的所有参数都可以被访问,无论是否传入更少或更多。

了解这一点,您可以将传递给scheduledFunction的任何参数 从第4个参数开始 作为将用于传递给{的参数{1}}。这可以通过使用Array#sliceFunction#call来实现(因为参数不是数组而是类似数组的对象,因此需要):

functionName

然后,您可以使用Function#apply调用var args = [].slice.call(arguments, 4); 将切片参数作为参数传递:

functionName

修改后的代码看起来像这样:

functionName.apply(null, args);

像这样使用它,注意不再调用function scheduleFunction(t, deltaT, functionName) { var timeout; var timeoutID; // Get the rest of the parameters (if any) // from the 4th one onwards var args = [].slice.call(arguments, 4); function scheduler() { // Call functionName, passing in all the extra parameters functionName.apply(null, args); // Etc... } scheduler(); } ,但传递给它的参数只是作为print的参数:

scheduleFunction

您可以通过修改调用console.log的方式来打印多个参数:

function print(string) { 
  console.log(string);
}

scheduleFunction(1000, 500, print, "Hello World!");
相关问题