Search code examples
javascriptecmascript-6symbolses6-class

In ES6, how to override a private method in a super class?


I'm learning about classes in ES6...

I'd like to use private properties, in some form, so that only certain methods can be called from an instance of a class.

For example using Symbol...

/* A.js */

const _privateMethod = Symbol('_privateMethod')
class A {
    [_privateMethod]() {
        return 'yup'
    }
    do() {
        return this[_privateMethod]()
    }
}

const a = new A()
a.do() /* yup */

..._privateMethod cannot be called directly. So far so good.

However, I am wondering how to then go about overriding _privateMethod in a class that inherits from A. For example, the following will not work:

/* B.js */

const _privateMethod = Symbol('_privateMethod')
class B extends A {
    [_privateMethod]() {
        return 'nope'
    }
}

const b = new B()
b.do() /* yup */

How is it recommended to do this?


Solution

  • Calling Symbol('_privateMethod') again creates a new, distinct symbol (even if it has the same description). You are creating a different method with a different key, not overwriting the original one.

    You will need to use the exact same symbol to define the method in the subclass. You can either get it from Object.getOwnPropertySymbols(A.prototype) or by exporting the _privatMethod symbol as a constant from A.js and importing it in B.js (together with the class A). However, if you want to make the class extensible, I would recommend to simply not use symbols at all.