![](/img/trans.png)
[英]How to use base class methods in a subclass of a Builtin JavaScript class in javascript
[英]Javascript subclass object not retaining properties / methods of base class
function Man(name){
this.name = name || 'John';
}
Man.prototype.getName = function(){
return this.name;
}
function Emp(id){
this.id = id;
}
Emp.prototype = Object.create(Man.prototype);
Emp.prototype.display = function(){
return this.id;
}
//Testing
var emp = new Emp(100);
emp.id ; // 100
emp.display() //100
然而,
emp.name // undefined
emp.getName() // undefined
emp instanceof Man // true, proves inheritance
为什么emp.name
和emp.getName()
undefined
为什么
emp.name
和emp.getName()
undefined
因为您永远不会将Man
应用于新的Emp
实例。 您还必须在子构造函数中调用父构造函数:
function Emp(id){
Man.call(this); // call parent constructor
this.id = id;
}
使用ECMAScript 6类,您将必须调用super
:
class Emp extends Man {
constructor(id) {
super();
this.id = id;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.