如何调用自身内部的函数
How to call function inside itself
我有一个函数,我想在最后一行结束后再次调用它。
如果我展示代码,也许会更容易理解。
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);
相关文章:
- 我可以从内部函数中产生吗?
- 从内部函数javascript内部分配外部函数的对象
- 将外部函数返回的id传递给内部函数
- 重复调用的同一函数会重置setTimeout内部函数
- Javascript中的内部函数作用域
- 对象内部函数内的对象文本的范围
- 内部函数不会为外部函数在 jQuery 中动态创建的元素赋值
- JavaScript 如何定义内部函数
- bluebird promise catch() 没有使用 Promise.CancelError 调用内部函数
- JavaScript 在内部函数中保留一个 var
- 如何使用Javascript访问内部函数
- 使用从内部函数返回的异步数据对外部函数返回promise
- Javascript对象看不到内部函数
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 如何将参数传递到内部函数中
- JavaScriptEs6在内部函数中引用了这一点
- 需要将内部函数绑定到元素的单击事件
- 将此对象传递给JavaScript中的内部函数
- JavaScript 面向对象的调用函数内部函数或调用函数 insede var
- 从内部函数内部突破while循环'的身体