繁体   English   中英

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.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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM