我正在尝试理解 javascript 中的继承
function baseClass(name) {
this.name = name;
this.getName = function() {
return this.name;
}
}
function subClass(id, company){
baseClass.call(this);
this.id = id;
this.company = company;
this.toString = function() {
return name + "\n" + this.id + "\n" + this.company;
}
}
subClass.prototype = Object.create(baseClass);
var s = new subClass();
s.toString(); //here the name property from the baseClass is not displayed.
如何正确实现继承(经典/原型(prototype))
最佳答案
首先,有两个小问题:
- 大小写在 JavaScript 中很重要。
Object.create
需要小写,并且您的函数名称不匹配(subClass
与SubClass
)。通常,构造函数名称都是大写的。 - 使用属性
this.name
(继承的)而不是变量name
(未定义) - 参见Javascript: Do I need to put this.var for every variable in an object?
How do correctly implement inheritance
将方法(不需要特权,构造函数范围内没有局部变量)移动到原型(prototype)对象上。并且让 SubClass.prototype
继承自 BaseClass.prototype
,而不是继承自 BaseClass
函数。
function BaseClass(name) {
this.name = name;
}
BaseClass.prototype.getName = function() {
return this.name;
};
function SubClass(id, company){
BaseClass.call(this);
this.id = id;
this.company = company;
}
SubClass.prototype = Object.create(BaseClass.prototype);
SubClass.prototype.toString = function() {
return this.name + "\n" + this.id + "\n" + this.company;
};
new SubClass().toString()
does not display the name property from the baseClass
您正在调用不带任何参数的构造函数。 id
、company
和 name
属性将具有 undefined
值。此外,您的 SubClass
甚至没有 name
参数,并且它不会将任何内容传递给 BaseClass
构造函数调用。
关于javascript - 实现 JavaScript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021577/