我想在同一个函数内部和外部调用一个函数。在 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 函数和重复函数内部的具体内容,这样的结构可能会更好:
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 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)