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

因为在第一个版本中,您正在访问未传递的函数参数,所以它们的值是未定义的。这不会产生错误。

在第二个示例中,您将取消引用到未定义的对象。如果你有一个未定义的值并试图访问它的属性,你总是会产生一个错误。

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
}

您可能想重新考虑如何使用它,但“快速修复”是将第二种情况下的构造函数更改为:

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 回答