Doubt with JavaScript arrow function

4

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

My question is, in that case would I have to use a conventional function, the arrow function would not work in this case?

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

console.log(obj.showName());
    
asked by anonymous 01.06.2017 / 22:23

1 answer

3

The best thing to do here 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 therefore can not point to itself.

You can create a similar scenario in which this would work, but it is full exercise, I am not seeing a use case that does not have to 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 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 (in proposal / study phase to implement in the language).

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

}
var obj = new Obj();
console.log(obj.showName()); // object
    
01.06.2017 / 23:03