Difference in Javascript attribute creation

Asked

Viewed 34 times

0

What is the real difference between creating these two ways?

function Pessoa() {
    this.nome = 'lucas'
}

and

function Pessoa() {
    nome = 'lucas'
}

When it comes to instantiating, there will be some difference?

  • It’s just that, or has some other context?

  • Yes, there will be differences, especially if you use Arrow Functions. In this case the this varies greatly, moreover the variable nome can be accessed from any other function (it will be a global variable in the scope of the main function, it would be the equivalent of a public type attribute in a class - you can even access using myObj.nome). In the second example the variable nome shall be local and may not be changed outside the scope.

1 answer

2


There’s a difference because the two things are different

In the second the name variable is declared as a global variable and in the console the new person instance is an empty object, the keyword this serves precisely to specify which context that variable is, in the first case, the name variables are in the context of the new instance of that constructor function

function Pessoa() {
  nome = 'lucas';
}

console.log(new Pessoa())

A more practical example:

function Pessoa(n) {
  nome = n
}

let objPessoa1 = new Pessoa('lucas');

console.log(objPessoa1.nome); //undefined
console.log(nome); //lucas

let objPessoa2 = new Pessoa('guilherme');

console.log(objPessoa2.nome); //undefined
console.log(nome); //guilherme

When the second Person instantiation is made the constructor function changes the global name variable, and does not create a new one that is within objPessoa2

Browser other questions tagged

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