"this" inside Arrow Function used as a method of an object does not point to the object

Asked

Viewed 41 times

1

The this of carro2 should not point to the context in which it was created (in the case within carro2)?

Follow an example with the this of function normal and other with the Arrow:

    const carro = {
        modelo: 'Fiesta',
        fabricante: 'Ford',
        nomeCompleto: function(){ 
            return `${this.fabricante} ${this.modelo}`
        } } 

        console.log(carro.nomeCompleto()) // Imprime normalmente
    
    
    const carro2 = {
        modelo: 'Fiesta',
        fabricante: 'Ford',
        nomeCompleto: () => {
            return `${this.fabricante} ${this.modelo}`
        } }
    
    console.log(carro2.nomeCompleto()) // Imprime Undefined

1 answer

2


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.

Browser other questions tagged

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