Javascript 子类不';t继承超类属性
在定义子类时,我得到了构造函数参数的typerorr:undefined,正如我看到的,它充当占位符。到底发生了什么以及如何解决Javascript 子类不';t继承超类属性,javascript,oop,inheritance,Javascript,Oop,Inheritance,在定义子类时,我得到了构造函数参数的typerorr:undefined,正如我看到的,它充当占位符。到底发生了什么以及如何解决 function Class(object) { this.name = object.name; } var myClass = new Class({ name: "ClassName" }) console.log(myClass.name); function SubClass(object) { this.name = obj
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:对象未定义通常,基类的原型上会有方法,因此更适合使用
SubClass.prototype=object.create(BaseClass.prototype)
,还可以在基类的构造函数中调用父构造函数,以便在父构造函数中找到对象.name
(这是由于未向子类.prototype=new class()传递任何内容而导致的错误)
这里有一些有用的参考资料
通常,基类的原型上会有方法,因此更适合使用SubClass.prototype=Object.create(BaseClass.prototype)
,并在基类的构造函数中调用父构造函数,以便在父构造函数中找到Object.name
(这是由于未将任何内容传递到SubClass.prototype=new Class()
中而导致的错误
这里有一些有用的参考资料
通常,基类的原型上会有方法,因此更适合使用SubClass.prototype=Object.create(BaseClass.prototype)
,并在基类的构造函数中调用父构造函数,以便在父构造函数中找到Object.name
(这是由于未将任何内容传递到SubClass.prototype=new Class()
中而导致的错误
这里有一些有用的参考资料
通常,基类的原型上会有方法,因此更适合使用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"