Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  82] [ 6]  / answers: 1 / hits: 11512  / 9 Years ago, tue, december 22, 2015, 12:00:00

In ES5, you could emulate a class with private and public variables like this:



car.js



function Car() {
// using var causes speed to be only available inside Car (private)
var speed = 10;

// public variable - still accessible outside Car
this.model = Batmobile;

// public method
this.init = function(){

}
}


But in ES6, you can no longer declare vars outside the constructor, making it actually HARDER to work with classes in a OOP way!?



You can declare variables in the constructor using this, but that makes them public by default. This is very weird since ES6 DOES have a get / set keyword!



class Vehicle {
constructor(make, year) {
// the underscore is nice, but these are still public!
this._make = make;
this._year = year;
}

// get and set can be handy, but would make more sense
// if _make and _year were not accessible any other way!
get make() {
return this._make;
}

get year() {
return this._year;
}
}

More From » class

 Answers
9

ES6 standard does not offer a new way for defining private variables.



It's a fact, that new ES6 class is simply syntactic sugar around regular prototype-based constructors.



get and set keywords are offering a way for simplified definition of ES5 custom getters and setters that were previously defined with a descriptor of Object.defineProperty()



The best you could do is to use those techniques with Symbols or WeakMaps



The example below features the use of a WeakMap for storing private properties.



// myModule.js
const first_name = new WeakMap();

class myClass {
constructor (firstName) {
first_name.set(this, firstName);
}

get name() {
return first_name.get(this);
}
}

export default myClass;


I'm referring to article, written by David Vujic What? Wait. Really? Oh no! (a post about ES6 classes and privacy) with the idea of using WeakMaps.


[#32044] Monday, December 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;