如何调用自身内部的函数

How to call function inside itself

本文关键字:内部 函数 何调用 调用      更新时间:2023-09-26

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

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

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
}

知道吗?

答案很简单,在updateQuantity函数中使用updateQuantity.call(this)就足够了——当我们使用call并添加this时,函数将重新启动,并记住以前调用updateQuantity的输入元素。

从问题的注释来看,您似乎想将值传递给递归方法调用。

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

看起来您正试图在函数体中获取DOM元素。

这是一个简单的例子:https://jsfiddle.net/c3kbu0j7/10/

HTML

<a href="#">element you want.</a>

JavaScript

$('a').on('click',function(){
    a(this);
});
var i=0;
function a(tar){
  console.log(tar);
  if(i<4){
    i++;
    a(tar);
  }
  i=0;
}

您可以使用requestAnimationFrame(),它在每帧调用函数。

HTML

<a href="#" id="link"></a>

JS-

const link = document.getElementById("link");
function myFunc(value) {
      ///////////////////
     // do stuff here //
    ///////////////////
    
    // call the function again with the same parameter
    requestAnimationFrame(myFunc(value));
}
link.addEventListener("mousedown", function () {
    myFunc(link);
}, false);

或者,如果您希望函数只被调用两次:

HTML

<a href="#" id="link"></a>

JS-

const link = document.getElementById("link");
let x = 0;
function myFunc(value) {
      ///////////////////
     // do stuff here //
    ///////////////////
    
    // call the function again but increase x so an infinite loop isn't created
    if (x < 1) {
        x++;
        myFunc(value);
    }
    else x = 0;
}
link.addEventListener("mousedown", function () {
    myFunc(link);
}, false);