JavaScript-访问父类中的子变量

时间:2018-09-05 21:00:05

标签: javascript class variables inheritance constructor

在JavasScript中,是否可以在子类中定义变量,然后在父类中访问变量?我想孩子的班级会像这样:

export default class ChildClass extends ParentClass {
    constructor() {
        this.path = 'register';
    }
}

用例场景是一个HTTP服务类,它作为父类包含了可重用的常规方法,而子类则定义了将被访问的确切路由。假设有可能,那么我该如何在父类中访问this.path

1 个答案:

答案 0 :(得分:1)

您不需要做任何特别的事情,就可以了。

如评论中所述,像这样设计您的类不一定有意义,因为对象的实际类可能不是那个子类。

class ParentClass {
  printPath() {
    console.log(this.path);
  }
}

class ChildClass extends ParentClass {
  constructor() {
    super();
    this.path = 'register';
  }
}

var c = new ChildClass();
c.printPath();
var p = new ParentClass();
p.printPath();