如何在JavaScript中的相同函数内部和外部调用函数

时间:2018-09-20 11:49:36

标签: javascript jquery

我想在同一个函数内部和外部调用一个函数。如何在javascript中使用?

JS:

someFunction(function repeat(result) {
    document.body.innerHTML += '<br>' + result.winner;
    if (result.winner) {
        someFunction(repeat);
    }
});
someFunction.repeat();

2 个答案:

答案 0 :(得分:1)

我想您想使用递归来实现它,这可能会对您有所帮助。更改条件并按预期输出代码。

function someFunction(result) {
     document.body.innerHTML += '<br>' + result;
     result--;
   
    if (result===0) {
       return;
     }
     
     return someFunction(result);
}
 someFunction(5);

答案 1 :(得分:1)

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函数内部到底还有什么,这样的结构可能会更好地工作:

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 );