如何在内部调用函数

cyp*_*ian 5 javascript jquery

最后一行结束后,我想在内部再次调用一个函数。

如果显示代码,也许会更容易理解。

function updateQuantity(){ 
    // further code where I change same data
    // and now I want to start function again but with remembering the input element that called it previously 
    updateQuantity(this);  // I tried it this way but it doesn't work
}
Run Code Online (Sandbox Code Playgroud)

任何的想法?

cyp*_*ian 6

答案很简单,updateQuantity.call(this)updateQuantity函数内部使用就足够了——当我们使用call和添加时this,函数会再次启动并记住之前调用的输入元素updateQuantity


Uzb*_*jon 4

From the comments to your question, it seems like you want to pass a value to your recursive method call.

function updateQuantity(val){
  // Do something with `val`
  val = val + 1;

  console.log(val);

  // And call it again with the value
  if(val < 5){
    updateQuantity(val);
  }
}

updateQuantity(1); // 2, 3, 4, 5
Run Code Online (Sandbox Code Playgroud)