0

クラスの質問とそのサブクラスがあります

    var Question = function(id, text){
        this.id = id;
        this.text = text;
}

Question.prototype.Display = function(){
    console.log("Entering Display");
}
var QType1 = function(question_obj){
    //this is true or false
    Question.call(this, question_obj.id, question_obj.settings.text) ;
    this.choices = question_obj.settings.choices;
    this.answers = question_obj.settings.answers;
}

//inherit Question
QType1.prototype = new Question();

以下のコードに変更すると、動作しません。なぜこれが起こっているのか誰にも説明できますか?

var Question = function(question_obj){
        this.id = question_obj.id;
        this.text = question_obj.setting.text;
}

Question.prototype.Display = function(){
    console.log("Entering Display");
}
var QType1 = function(question_obj){
    //this is true or false
    Question.call(this, question_obj) ;
    this.choices = question_obj.settings.choices;
    this.answers = question_obj.settings.answers;
}

//inherit Question
QType1.prototype = new Question();
4

1 に答える 1

1

最初のバージョンでは、渡されなかった関数の引数にアクセスしているため、それらの値は未定義です。これはエラーを生成しません。

2 番目の例では、未定義のオブジェクトに逆参照しています。未定義の値があり、そのプロパティにアクセスしようとすると、常にエラーが発生します。

foo(); // no arguments

function foo(a,b) {
    // 'a' is undefined, so is 'b'
    console.log(a);             // this is fine, you just get undefined
    console.log(b.doesntExist); // this will throw the error you are seeing
}

それをどのように使用しているかを再考したいかもしれませんが、「簡単な修正」は、2番目のケースのコンストラクターを次のように変更することです。

var Question = function(question_obj){
    if(question_obj !== undefined) { // now you know it's safe to dereference
        this.id = question_obj.id;
        this.text = question_obj.setting.text;
    }
}
于 2013-11-03T22:45:27.057 に答える