当我在 Javascript 中编写循环检查代码时,如何避免在定义这些函数之前使用它们?

How do I avoid using these functions before they are defined when I'm coding a circular check in Javascript?

我不断发现自己处于这些循环中,我正在处理用户输入以确保我得到预期的结果。但是,如果不在函数定义之前调用函数,我不知道该怎么做,这给了我 eslint 错误:no-use-before-define.

function tryAgain(){
  alertBadInput();
  getInput();
}

function getInput(){
  var input = askForInput();
  if (input === 'bad') {
    tryAgain();
    return;
  }
  processInput(input);
}

无论我以何种顺序定义这两个函数,其中一个函数在定义之前会调用另一个函数。

这在语法上似乎是有效的,但考虑到 eslint 错误,如果我希望避免该错误,我可以使用什么其他模式?

虽然两个函数相互调用可能没问题,但您最好使用 while 循环来清楚(这就是它的用途)并遵守编码标准以避免错误完全一样:

function getInput() {
    var no_valid_input = true;
    var input = null;
    while (no_valid_input) {
        input = askForInput();
        if (input !== 'bad') {
            no_valid_input = false;
        } else {
            alertBadInput();
        }
    }
    processInput();
}

工作示例:

function processInput() {
    return alert('Yep, processing...');
}
function alertBadInput() {
    return alert('Nope');
}
function askForInput() {
    return prompt('What?');
}

function getInput() {
    var no_valid_input = true;
    var input = null;
    while (no_valid_input) {
        input = askForInput();
        if (input !== 'bad') {
            no_valid_input = false;
        } else {
            alertBadInput();
        }
    }
    processInput();
}

getInput();

禁用错误

虽然它并没有真正解决问题,但针对特定用例禁用它可能是有意义的。

// eslint-disable-next-line no-use-before-define

这样使用:

function tryAgain(){
  alertBadInput();
  // eslint-disable-next-line no-use-before-define
  getInput();
}

function getInput(){
  var input = askForInput();
  if (input === 'bad') {
    tryAgain();
    return;
  }
  processInput(input);
}

用例

我不得不在带有 class 的模块中使用它,我不想在其中公开我的 class 特定函数(格式与以下代码类似)。翻转 class 和函数会产生相同的 eslint 错误。

它将是:

  • prepareRequest 之前,其中 Requestprepare 使用,或者
  • Requestprepare 之前,其中 prepareRequest 使用。

这显然是一种简化,但为您提供了总体思路:

// function that I don't export
function prepare(request) {
    // eslint-disable-next-line no-use-before-define
    if (request instanceof Request) {
        return JSON.stringify(request.obj)
    } else {
        return new TypeError('Wrong type given, expected Request')
    }
}

// class that export that uses the prepare function
class Request{
    constructor() {
        this.obj = {}
    }
    
    doSomething() {
        const request = prepare(this)
        // do something with request
    }
    
    addX(x) {
        this.obj.x = x
    }
}

module.exports = Request