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
2 Answers
Reset to default 4It 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
版权声明:本文标题:oop - How to access the super-class's private member in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744900329a2631305.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论