Javascript子类对象不保留基类的属性/方法

Javascript subclass object not retaining properties / methods of base class

本文关键字:属性 方法 基类 保留 子类 对象 Javascript      更新时间:2023-09-26
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.nameemp.getName()来得undefined

为什么emp.nameemp.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;
    }
}