5
I’m looking for a way to make both attributes and methods invisible so they’re not accessible from outside the class. But I also wanted to use the modern approach to do this (class Nomeclass{}). After many attempts I made a different approach to everything I found: although it works exactly as I need it, and, in my view, it becomes much simpler and readable, I don’t know if this is valid and/ or conventional.
Can I do that? Or is there some convention that prohibits this kind of approach?
Watch the code carefully:
'use strict';
//O objetivo dessa class é tornar os dados restritos
function ExemplePrivate(value){
var _value = value; //Privado
this.set_value = function(val){
//Poderá fazer uma validação antes
_value = val;
}
this.get_value = function(){
//Poderá fazer uma validação antes
return _value;
}
}
//Class filha que será pública
class ClassPublic extends ExemplePrivate{
//adicional code
}
var cPublic = new ClassPublic('A class filha foi <b>instanciada</b>');
document.querySelector('#p1').innerHTML = cPublic.get_value();
cPublic.set_value('A class filha foi <b>modificada</b>');
document.querySelector('#p2').innerHTML = cPublic.get_value();
// Note que o resultado é bloqueado
document.querySelector('#p3').innerHTML += cPublic._value+".";
#p3{color:red}
<!-- Look in JS -->
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"> O resultado para <b>cPublic._value</b> tem que ser <b>undefined</b> porque é invisível: </p>
It seems to me that the question is not about private class but about private fields/methods
– Isac
You can explain better in your example, by instantiating the class
var cPublic = new ClassPublic
what you want to be visible?– Sergio
Note that this example has the result as expected. And, it is working correctly. Answering your question: Only _value must be private, the rest are functions that manipulate it.
– Mr Genesis