How to define private attributes in a constructor function using javascript

Asked

Viewed 1,285 times

3

In javascript we can have the constructor functions that are of type Function, with them we can instantiate objects as in the following example:

function Pessoa(nome="Usuário Anonimo", idade = 00, cor) {
    //com o this podemos criar atributos e funções para serem acessados de forma pública
    this.falar = function() {
        console.log("Olá eu sou " + nome + " tenho " + idade + " Anos")
    }

    // podemos fazer os retornos de atributos da função por meio de métodos públicos ou até mesmo atributos públicos como this.nome = nome
    this.getCor = function(){
        return this.cor
    }

    this.setCor = function(cor){
        this.cor = cor
    }

}

const anonimo = new Pessoa
anonimo.falar()
anonimo.setCor("pardo")
console.log(anonimo.getCor())

// outra execução

const pedro = new Pessoa("Pedro ", 35, "Rosa")
pedro.falar()
// nesse caso a saída é undefined pois teríamos que definir this.cor = cor
// nesse caso iria referenciar a assinatura da function
console.log(pedro.getCor())

In other languages like Java we can define the visibility and permissibility of attributes through reserved words like: private, protected or public and depending on whether it is one or the other we can work on direct returns instancia.atributo or class.getAtribute how we can assign such contexts within a constructor function?

Reference: object oriented mozila

2 answers

2


This is not usually done in Javascript.

There is a proposal in phase 3 of Ecmascript to include the private access method in the classes, but for now it is just that, a proposal.

By convention, many programmers use an underscore at the beginning of a variable declaration to indicate that such a property should not be accessed directly, in your example it would be _nome and _idade.

Aliases, different programming languages, different conventions. Javascript has properties, not attributes, getCor and setCor is a Java convention to enable the creation of a logic before the access/assignment of an attribute, but in languages that use properties, you will rarely see the use of methods to implement this logic.

You can implement this layer directly on getter and in the Setter of property. Since using getters and setters in properties does not require the use of any different syntax, you only need to implement these getters and setters if you use them. There is no need to create them beforehand to avoid the possible refactoring of the code.


Edit

And then, less than a month after posting the reply, the proposal was accepted and it is now possible to create private Javascript properties with the following syntax:

class Retangulo {
  #altura;
  #largura;

  constructor(altura, largura) {
    this.#altura = altura;
    this.#largura = largura;
  }

  get area() {
    return this.#altura * this.#largura;
  }
}

const ret = new Retangulo(3, 5);
console.log('area:', ret.area);

Notice that #altura and #largura are not accessible outside the class.

This new feature is now available in the latest versions of Chromiun-based browsers, as well as in transcomputers such as Babel and Typescript.

1

A private property of a class is a variable that can only be accessed by it, right? So the variables nome, idade and cor are already private, since only exist within the function, if you want to create others without receiving as parameter, just create within Pessoa with var, let and const

What’s probably happening is that you believe cor and this.cor are the same variable, but are not, cor is a variable that exists only within the scope of the constructor function, while this.cor is a property of the object this which is returned to the instantiator and therefore is public

All properties of an object are public, that is, public is whatever is in the this and private is what is created within the function. The other access modifiers do not exist, the attribute name can be prefixed with _ when that property needs to be public to be accessed outside the class in other framework/library functions, however the (developer) user should not use them directly

But I don’t quite understand what you want, if you want cor be public, just add this.cor = cor or even call this.setCor(cor) within the function Pessoa. If you want to cor is private to be accessed only by methods getter and Setter, just change this.cor for cor

Browser other questions tagged

You are not signed in. Login or sign up in order to post.