子类不继承超类属性

时间:2013-11-09 00:11:43

标签: javascript oop inheritance

在定义子类时,我得到了TypeErorr:undefined用于构造函数参数,正如我所见,它充当占位符。到底发生了什么以及如何解决它?

function Class(object) {
    this.name = object.name;
}

var myClass = new Class({
    name: "ClassName"
})

console.log(myClass.name); 

function SubClass(object) {
    this.name = object.name;
}

SubClass.prototype = new Class();
SubClass.prototype.constructor = SubClass;

var mySubClass = new SubClass({
    name: "SubClassName"
})

// TypeError:object is undefined

1 个答案:

答案 0 :(得分:3)

通常你的基类会在其原型上有方法,所以使用SubClass.prototype = Object.create(BaseClass.prototype)更合适,并在基类的构造函数中调用你的父构造函数,以便找到object.name在父构造函数中(这是你得到的错误,因为没有任何内容传递到SubClass.prototype = new Class()

function Class(object) {
    this.name = object.name;
}

Class.prototype.sayName = function () {
    return this.name;
}

var myClass = new Class({
    name: "ClassName"
});

console.log(myClass.name); 

function SubClass(object) {
    // call parent constructor with context of the new SubClass instance
    Class.call(this, object);
}

SubClass.prototype = Object.create(Class.prototype);
SubClass.prototype.constructor = SubClass;

var mySubClass = new SubClass({
    name: "SubClassName"
});

console.log(mySubClass.sayName());
// > "SubClassName"

以下是一些有用的参考资料