Difference in creating attributes in Javascript

0

What's the difference between creating these two ways?

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

and

function Pessoa() {
    nome = 'lucas'
}

Is it time to instantiate to make a difference?

    
asked by anonymous 03.06.2018 / 07:42

1 answer

2

It has a difference because the two things are different

In the second the variable name is declared as a global variable and in the console the new instance of person is an empty object, the keyword this serves precisely to specify to which context that variable is, in the first case, the variables name 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 instantiation of Person is made, the constructor function changes the global variable name, and does not create a new one that is within objPessoa2

    
03.06.2018 / 08:21