简体   繁体   English

如何在JavaScript中访问超类的私有成员?

[英]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.

相关问题 如何在子类组件模板中访问超类属性? 角度的 - How to access super-class property in sub-class component template? Angular 如何在JavaScript中继承私有成员? - How to inherit a private member in JavaScript? 从JavaScript中的私有方法访问成员变量 - Access a member variable from a private method in JavaScript javascript函数无法访问对象的私有成员 - javascript function is not able to access private member of the object 可以在子类的方法内部使用“ super”来调用相应的父类方法而无需直接引用吗? - Could “super” be used inside a method of subclass to call the corresponding method of super-class without direct referencing? Javascript 基类如何访问派生类成员? - Javascript how can base class access derived class member? 在javascript中继承和使用超类的构造函数 - Inherit and use super class's constructor in javascript 仅在具有该 class 实例的 class 内部访问 class 的私有成员 - Access to private member of a class only inside a class that has an instance of that class 打字稿:超类构造函数的成员变量 - typescript: member variables from super class's constructor 如何从 TypeScript 中相同的 class 的 static 方法访问 class 的私有成员? - How to access private member of a class from a static method of the same class in TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM