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?
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?
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 javascript oop
You are not signed in. Login or sign up in order to post.
It’s just that, or has some other context?
– Maniero
Yes, there will be differences, especially if you use
Arrow Functions
. In this case thethis
varies greatly, moreover the variablenome
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 usingmyObj.nome
). In the second example the variablenome
shall be local and may not be changed outside the scope.– Valdeir Psr