Javascript类继承奇怪的行为

时间:2013-11-03 22:26:19

标签: javascript

我有一个课程问题及其子课程

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

1 个答案:

答案 0 :(得分: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;
    }
}