Doubt with Javascript Arrow Function

Asked

Viewed 284 times

5

In the code below, the method showName() naturally return undefined, because it will fetch a name property in the scope where the obj is inserted.

My question is, in that case I would necessarily have to use a conventional Function, a Arrow Function would not serve in this case?

var obj = {
  nome: 'object',
  showName: () => {
    return this.nome
  }
}

console.log(obj.showName());

  • Within the console.log shouldn’t be showName()?

  • Yes, I’ve changed, thank you

  • when using Arrow Function, dispenses with the return.

  • 1

    Possible duplicate of Undefined variable, even if defined. PS: this will not work in this case, I am analyzing the Cmas to see details and update the answer, I will get you.

  • @Guilhermenascimento my doubt is how best to write this and not the question of the scope.

  • @Felipecoelho so I’m reading in Cma to see if there is another way, not speaking of scope, I’m talking about what is possible so far as ecmascript ;)

  • @Guilhermenascimento ok, thank you

Show 2 more comments

1 answer

5


The best thing in this case is to use a function "normal". This is a dead end case. The object is created in a given context, the Arrow Function will use the context at the time of creation and can therefore not point to itself.

You can create a similar scenario where that would work, but it’s full exercise, I’m not seeing a use case that you can’t do otherwise:

var obj = (function() {
    this.nome = 'object';
    this.showName = () => {
        return this.nome;
    }
    return this;
}).call({});

console.log(obj.showName()); // object

The same no longer applies to classes, which would be more interesting than a simple object (because if you have Arrow functions you can benefit from ES6 classes). In this case the class creates its own context and the Arrow Function would be very useful:

class Obj {
  constructor() {
    this.nome = 'object',
      this.showName = () => {
        return this.nome;
      }
  }
}
var obj = new Obj();
console.log(obj.showName()); // object

Or using notation with class properties (proposal/study phase to implement in language).

class Obj {
  nome = 'object';
  showName = () => {
    return this.nome;
  }

}
var obj = new Obj();
console.log(obj.showName()); // object

Browser other questions tagged

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