Lexical this
Until arrow functions, every new function defined its own this
value
(a new object in case of a constructor, undefined in strict mode
function calls, the context object if the function is called as an
"object method", etc.). This proved to be annoying with an
object-oriented style of programming.
From : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
This is why, when you write:
this.setState = function() {};
function(pos) {
this.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude
})
}
The this
in this.setState
inside the function is set to {}
(an empty object).
When you write it with the =>
notation instead, the this is shared with the outside of the function, which is equivalent to :
this.setState = function() {};
var self = this;
function(pos) {
self.setState({
lat: pos.coords.latitude,
lng: pos.coords.longitude
})
}
or you could also use function(pos){ /* Stuff here */ }.bind(this);