admin管理员组

文章数量:1410697

In a class, how do I access its base-class's private field, say #property?

class Base {
  #property = '1.618'
  toString() {
    return Base.name
  }
}
class X extends Base {
  thisWorks() {
    return super.toString()
  }
  toString() {
    return super.#property // SyntaxError: Unexpected private field
  }
}
console.log(`${new X}`)

In a class, how do I access its base-class's private field, say #property?

class Base {
  #property = '1.618'
  toString() {
    return Base.name
  }
}
class X extends Base {
  thisWorks() {
    return super.toString()
  }
  toString() {
    return super.#property // SyntaxError: Unexpected private field
  }
}
console.log(`${new X}`)

Share Improve this question edited Apr 26, 2019 at 10:42 P Varga asked Apr 26, 2019 at 10:13 P VargaP Varga 20.3k13 gold badges77 silver badges118 bronze badges 2
  • it is impossible I think. From object oriented perspective, it needs to be protected or public to be accessed. – duc mai Commented Apr 26, 2019 at 10:25
  • just fyi, protected member access is doable, I actually did it once as an experiment, but it's very kludgy and performance suffers. basically a wrapper for building a class which is fed functions and properties on a prototype object, which are then weakmapped and checked against function.caller in getters for each method name however function.caller is now deprecated and doesn't look like there will be a replacement – Nolo Commented May 4, 2021 at 5:03
Add a ment  | 

2 Answers 2

Reset to default 4

It is impossible:

It means that private fields are purely internal: no JS code outside of a class can detect or affect the existence, name, or value of any private field of instances of said class without directly inspecting the class's source, unless the class chooses to reveal them. (This includes subclasses and superclasses.)

Base would have to deliberately expose its #property in some other way, like through a method.

In OOP you can not access private method or property outside of the class even when you extend. But you can access protected method of parent class in child class.

本文标签: oopHow to access the superclass39s private member in JavaScriptStack Overflow