According to this excerpt from the documentation:
When a Function is called as a method of an Object, its this
is set to the Object the method is called on.
In free translation:
When a function is called as a method of an object, the this
this is set to the object in which the method is called.
That’s why the first case works, because within the function nomeCompleto
, the this
refers to the object carro
:
const carro = {
modelo: 'Fiesta',
fabricante: 'Ford',
nomeCompleto: function () {
console.log(this === carro); // true
return `${this.fabricante} ${this.modelo}`;
}
};
console.log(carro.nomeCompleto()); // Ford Fiesta
For the second case, the documentation on Arrow functions clearly states that they are not suitable for use as methods ("Arrow Function Expressions are Ill suited as methods"), precisely because they do not this
to the object in which they are, and in this passage there is an example explaining that the this
is not set to the object.
To understand better, consider the object below:
const obj = {
valor: this
}
console.log(obj.valor == globalThis); // true
Inside the object obj
, the this
is the global object. And as a Arrow Function doesn’t have his own this
and uses the this
of the scope in which she is, then a Arrow Function within this object will use the global object as this
. And that’s what happens in the second case:
const carro2 = { // não cria um novo escopo, this é o objeto global
modelo: 'Fiesta',
fabricante: 'Ford',
nomeCompleto: () => { // aqui o this é o objeto global
console.log(this == globalThis); // true
return `${this.fabricante} ${this.modelo}`;
}
};
console.log(carro2.nomeCompleto()); // undefined
That is, you are trying to access the properties fabricante
and modelo
of the global object, and as they were not defined, the result is undefined
.