[英]How to access the super-class's private member in JavaScript?
In a class
, how do I access its base-class's private field, say #property
? 在一个
class
,如何访问其基类的私有字段,例如#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 OOP you can not access private
method or property outside of the class even when you extend. 在OOP中,即使扩展,也不能在类外部访问
private
方法或属性。 But you can access protected
method of parent class in child class. 但是您可以在子类中访问父类的
protected
方法。
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.
这意味着私有字段纯粹是内部的:类之外的任何JS代码都无法检测或影响所述类实例的任何私有字段的存在,名称或值,而无需直接检查类的来源,除非该类选择显示它们。 。 ( This includes subclasses and superclasses.)
( 这包括子类和超类。)
Base
would have to deliberately expose its #property
in some other way, like through a method. Base
必须不得不以其他方式(例如通过一种方法)故意公开其#property
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.