Home > Back-end >  Inherited value overwriting getter
Inherited value overwriting getter

Time:01-21

I was messing around with classes when I found this weird behaviour:

class A {
  test = 1
}

class B extends A {
  get test () {
    return 2
  }
}

const b = new B()

console.log(b.test)

The logical answer to the output should be 2 but when running the code, the output is 1.

Am I missing something? Is this intended javascript behaviour? I could not find anything in the MDN documentation about this.

I found this question which might be related to mine but it did not include any work arounds.

CodePudding user response:

You would have to redefine the value of test inside of B.

class A {
  test = 1
}

class B extends A {
  test = 2 // redefine
}

const b = new B()

console.log(b.test) // 2

If you check out MDN - References - JavaScript - Functions - getter, you will see that this is not possible.

Description


Note the following when working with the get syntax:

  • It must not appear with a data entry for the same property e.g. the following is forbidden
    {
      x: /* … */, get x() { /* … */ }
    }
    

CodePudding user response:

As pointed out by Mr. Polyshirl and Sebastian Simon, it is not possible to overwrite an inherited property using a getter. My "solution" was to use plain-old functions instead of getters and setters.

So, for example, instead of using

class Example {
  method = 'value'
}

const example = new Example()

console.log(example.method)

use

class Example {
  #method = 'value'

  getMethod () {
    return this.#method
 }

 setMethod (method) {
   this.#method = method

   // Use return this to allow for method chaining
   return this
 }
}

const example = new Example()

console.log(example.getMethod())

or

class Example {
  getMethod () {
    return 'value'
  }
}

const example = new Example()

console.log(example.getMethod())

  • Related