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?
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?
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