javascript - 我怎样才能实现继承链?

标签 javascript oop

继承有问题。如何实现从 Some Pencil 到 Another Pencil 的类型继承?需要:pen3.type//common

  class Pencil {
     constructor(color) {
      this.color = color;
    }
    intro() {
      console.log(`this is ${this.color} pencil`);
     }
    };

    class SomePencil extends Pencil {
     constructor(color, type) {
      super(color);
       this.type = type;
     }
    };
    class AnotherPencil extends SomePencil {
      constructor(color,type) {
       super(color, type);
     }
    };

    let pen1 = new Pencil();
    let pen2 = new SomePencil("red", "common");
    let pen3 = new AnotherPencil("green");

    console.log("type" in pen3); // true

最佳答案

继承只会继承属性而不是值,除非它们是在类定义本身中设置的。例如

class SomePencil extends Pencil {
 constructor(color, type) {
  super(color);
   this.type = type || 'common'; // Setting a default value if type is not passed
 }
};

设置默认值的新方法

class SomePencil extends Pencil {
 constructor(color, type = 'common') {
  super(color);
   this.type = type;
 }
};

引用jsfiddle

关于javascript - 我怎样才能实现继承链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53285056/

相关文章:

javascript - Javascript 原型(prototype)设计错​​误 "Class"- 不是函数且 undefined variable

java - 如何通过依赖注入(inject)和垃圾收集来防止循环引用?

c++ - 如何在其父类中调用子类?

javascript - 当 URL 以 "//"为前缀时,Electron 无法加载外部 SVG 文件

javascript - 是否有 nodejs 的 Jack 等效项?

javascript - 在 javascript 对象上应用架构

java - OOP - 继承 [Java]

javascript - 为什么对象上的 `.show` 属性会破坏基于该对象的数据绑定(bind)?

Javascript,点击时触发功能

c# - 在 .NET : good, 中隐藏继承的通用接口(interface)成员是坏的还是丑的?