0

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

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: 对象未定义

4

1 回答 1

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"

这里有一些有用的参考资料

于 2013-11-09T01:09:29.850 回答