+ 1

Private atributes em JavaScript

I'm new in JavaScript, so I am look for a way of create a private class to do a atrube and/or method to be unvisible of outside. But I need that in new syntax of class because is more easy I think. So there is two days that I'm try this. Look wich I achived to do: 'use strict'; //This class take all data private function ExemplePrivate(value){ var _value = value; this.set_value = function(val){ //Do you most to do validation before _value = val; } this.get_value = function(){ //Do you should to do validation before return _value; } } //This class take all data public and extends the private class class ClassPublic extends ExemplePrivate{ //adicional code } function runLoading(){ //Run as soon as loadin page var cPublic = new ClassPublic('The child class has been <b>instanceid</b>'); document.querySelector('#p1').innerHTML = cPublic.get_value(); cPublic.set_value('The child class has been <b>update</b>'); document.querySelector('#p2').innerHTML = cPublic.get_value(); // Look that if try take _value atribute show as undefined document.querySelector('#p3').innerHTML = `Result for <b>cPublic._value</b>: ${cPublic._value}.`; Here you are my question: Can I use my syntax in this way? Why? Look the code in Sololearn view: https://code.sololearn.com/WCr4Dd182OY8

8th Sep 2018, 12:59 PM
Mr Genesis
Mr Genesis - avatar
1 Odpowiedź
+ 2
function ExemplePrivate() { // code } FROM ABOVE: extending directly from a constructor function isn't the right way. It's going to break the internal workings of how class works. HOWEVER: You could rather inherit from a normal function which returns a class. Making that function a higher order function capable of adding features to the class before extending from it into another class. e.g; function modifyClass() { return class ExemplePrivate { // code } } SOLUTION => By default classes have 'getters' and 'setters' accessor properties, which allow you to create private interfaces. Some code shall we? class User { constructor(name) { // invokes setter this._name = name; } get name() { return this._name; } set name(value) { this._name = value; } } let user = new User("Ben"); console.log(user.name); //=> Ben BONUS TIP Even though getters/setters are methods, they are invoked as data properties.
26th Jan 2019, 1:12 AM
Benneth Yankey
Benneth Yankey - avatar