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
Within the
console.log
shouldn’t beshowName()
?– Jéf Bueno
Yes, I’ve changed, thank you
– Felipe Coelho
when using Arrow Function, dispenses with the
return
.– BrTkCa
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.
– Guilherme Nascimento
@Guilhermenascimento my doubt is how best to write this and not the question of the scope.
– Felipe Coelho
@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 ;)
– Guilherme Nascimento
@Guilhermenascimento ok, thank you
– Felipe Coelho