Arrow function isn't getting the value of a object property

51 views Asked by At

I'm trying to use a arrow function inside of a JS object, but it isn't getting the value of a object property. However, if I use a traditional function expression, it works properly.

Here's an example, first using a arrow function:

const obj = {
    name: "StackOveflow",
    simpleMethod: () => `Hello, ${this.name}!`
};

console.log(obj.simpleMethod());

The output is:

Hello, undefined!

Now using a traditional function expression:

const obj = {
    name: "StackOveflow",
    simpleMethod: function () {
        return `Hello, ${this.name}!`
    }
};

console.log(obj.simpleMethod());

The output is:

Hello, StackOveflow!

Why the arrow function doesn't get the name of the property?

Was expecting that the arrow function would get the value of the property, working in the same way as the traditional function expression

0

There are 0 answers