javascript - How to create private variables and methods inside a class ES6? -
this question has answer here:
- private properties in javascript es6 classes 24 answers
how create private variables , methods using es6 class should access public methods of same class.
class myclass { constructor() { this.publicvar = "i public"; //some private variable e.g privtevar1 = "i private1"; privatevar2 = "i private2"; this.publicmethod = () => { //it should have accesses private variables , methods console.log(privatevar1, privatevar2) }; //similarly need create privatemethod } render() { //it should have access private variables } }
as noticed @yibuyisheng can use symbols create unaccessible references properties. can create private method well.
var privatemethod = symbol('private'); class someclass { constructor() { } [privatemethod]() { // private actions } render() { // call private method this[privatemethod]() } }
symbol creates unique reference , can used property name. , property or method called using it. possible because es6 introducing computed properties syntax , can use variables dynamic properties definition.
if not exposing symbol others, can call it.
Comments
Post a Comment