簡體   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