How to Prevent Inheritance of Specific Method?

Viewed 2912

Say I have two classes, A and B. B extends A and therefore inherits all of its methods. I can override them if I want to as well. My question is whether or not I can prevent B from inheriting a specific method of A. What I've tried so far looks like this.

// setup
class A {
  constructor(x) {
    this.x = x;
  }

  valueOf() {
    return this.x;
  }

  toString() {
    return `{x:${this.x}}`;
  }
}

class B extends A {
  constructor(x) {
    super(x);
    delete this.valueOf;
  }
}

delete B.prototype.valueOf;

// example
const a = new A(42);
const b = new B(42);

// should work
console.log(a.valueOf());
// should throw TypeError, not a function
console.log(b.valueOf());

6 Answers
Related