简体   繁体   中英

JavaScript - Accessing a child variable in a parent class

In JavasScript, is it possible to define a variable in a child class, then access it in a parent class? I imagine the child class would look something like this:

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

A use-case scenario is an HTTP service class as the parent that contains general, reusable methods and a child class that defines the exact route that will be accessed. Assuming it's possible, how could I then access this.path in the parent class?

You don't need to do anything special, it just works.

As mentioned in the comments, it doesn't necessarily make sense to design your classes like this, since the actual class of the object might not be that child class.

 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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