简体   繁体   中英

How to extend a class property inherited from parent class in ES6?

I have the follow code:

class Parent {
    some_class_property = [1,2,3];

    some_other_methods(){...}
}

class Child extends Parent {
    some_class_property = super.some_class_property.push(4);
}

The console gives me a syntax error, saying that the keyword super is unexpected.

If class properties are allowed in ES6, then what's the point not allowing it to be extended in child classes? If this is not the right way to do it, then how? Thanks.

It looks like super references are not permitted inside class fields, which is why your current code throws an error.

But, the some_class_property is put onto the instantiated object itself in the superclass constructor (well, in the class field, which is effectively syntax sugar for putting it onto the object in the superclass constructor), which means you can reference it in the child class by referencing this.some_class_property . You aren't referencing a shadowed method or property, so super isn't needed:

 class Parent { some_class_property = [1, 2, 3]; } class Child extends Parent { some_class_property = this.some_class_property.push(4) } const c = new Child(); console.log(c.some_class_property);

Also keep in mind that .push returns the new length of the array, which is why the result of the above snippet is 4 . (If you wanted to make a copy of the some_class_property array, for whatever reason, instead use some_class_property = [...this.some_class_property, 4] )

The time to use super is when a property exists on the child instance, or the child prototype, but you want to reference a property on the parent prototype, eg:

 class Parent { method() { console.log('parent method'); } } class Child extends Parent { method() { console.log('child method'); } invokeParentMethod() { super.method(); } } const c = new Child(); c.method(); c.invokeParentMethod();

Public and private properties are Javascript features at an experimental stage (ES11?). For the past few years for ES6, people have been doing this:

class Parent {
    constructor(x){
        this.property1 = [1,2,3];
        ...
    }
    some_other_methods(){...}
}
Parent.property2 = [4,5,6];                 // to access: Parent.property1
Parent.prototype.property3 = [7,8,9];       // to access: obj.property2

class Child extends Parent {
    constructor(x){
        super(x);
        // ...
    }
    some_other_methods(){...}
}

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