0

なぜこのようにコンパイルするのですか?

this.setAlunos = function(alunos){
    if(this.getTurma() > 0){
        this.alunos = alunos.split(",");
    }
    else{
        throw "you must set a 'turma' before inserting students on it";
    }
};

そして、これはしませんか?

this.setAlunos = function(alunos){
    this.getTurma() > 0 ? this.alunos = alunos.split(",") : throw "you must set a 'turma' before inserting students on it";
};
4

1 に答える 1

2

三項演算子でやろうとしているように、実際に三項演算子の内部で直接エラーをスローすることはできません。throwただし、次のように無名関数でラップすることはできます。

this.setAlunos = function(alunos){
    this.getTurma() > 0 ? this.alunos = alunos.split(",") : (function(){throw "you must set a 'turma' before inserting students on it"}());
};

その後、正しく動作します。ただし、何かができるからといって、そうすべきだとは限りません。コードはずっと読みやすいので、以前のままにしておくことをお勧めします。

于 2012-11-28T17:17:22.643 に答える