I'm trying out ES6 and want to include a property inside my function like so
var person = { name: "jason", shout: () => console.log("my name is ", this.name) } person.shout() // Should print out my name is jason
However, when I run this code console only logs my name is
. What am I doing wrong?
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.
Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.
Short answer: this
points at the nearest bound this
- in the code provided this
is found in the enclosing scope.
Longer answer: Arrow functions do not have this
, arguments
or other special names bound at all - when the object is being created the name this
is found in the enclosing scope, not the person
object. You can see this more clearly by moving the declaration:
var person = { name: "Jason" }; person.shout = () => console.log("Hi, my name is", this);
And even more clear when translated into a vague approximation of the arrow syntax in ES5:
var person = { name: "Jason" }; var shout = function() { console.log("Hi, my name is", this.name); }.bind(this); person.shout = shout;
In both cases, this
(for the shout function) points to the same scope as person
is defined in, not the new scope that the function is attached to when it is added to the person
object.
You cannot make arrow functions work that way, but, as @kamituel points out in his answer, you can take advantage of the shorter method declaration pattern in ES6 to get similar space savings:
var person = { name: "Jason", // ES6 "method" declaration - leave off the ":" and the "function" shout() { console.log("Hi, my name is", this.name); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With