如何在javascript中调用同一函数内部的函数 [英] How to call a function inside same function and outside in javascript
本文介绍了如何在javascript中调用同一函数内部的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在同一个函数内外调用一个函数。如何在javascript中使用?
I want to call a function inside that same function and outside also. How does it in javascript?
Js:
someFunction(function repeat(result) {
document.body.innerHTML += '<br>' + result.winner;
if (result.winner) {
someFunction(repeat);
}
});
someFunction.repeat();
推荐答案
var someFunction = function( callback ) {
// Do some things that belong to someFunction, like creating the result object.
var result = {
winner: true
};
// Call the repeat function, using the result as the parameter.
callback( result );
};
var endless_loop_protection = 0;
var repeat = function( result ) {
// Write the result somewhere
console.log( result.winner + ': ' + endless_loop_protection );
// faking the if clauses that prevent the endless loop.
endless_loop_protection += 1;
if ( result.winner && endless_loop_protection < 10 ) {
// Do everything again if there's still a winner in the result.
someFunction( repeat );
}
};
someFunction( repeat );
根据someFunction函数和repeat函数的确切含义,这样的结构可以更好地工作:
Depending on what exactly else is inside the someFunction function and the repeat function, a structure like this could work better:
var get_result = function() {
// Create a random result.
return {
winner: Math.random() < 0.5
};
};
// This will keep looping until get_result returns a result with winner = true.
// So the amount of times this will log is random each time you call it.
var handle_results_until_winner = function( get_result ) {
var result = get_result();
console.log( result.winner );
if ( !result.winner ) handle_results_until_winner( get_result );
};
handle_results_until_winner( get_result );
这篇关于如何在javascript中调用同一函数内部的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文