javascript - How to create private variables and methods inside a class ES6? -


this question has answer here:

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

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -