![](/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.