I can't seem to understand why an arrow function within an object literal is invoked with window
as the context for this
. Any insights on this would be greatly appreciated.
var arrowObject = {
name: 'arrowObject',
printName: () => {
console.log(this);
}
};
// Outputs: Window {external: Object, chrome: Object ...}
arrowObject.printName();
On the other hand, here's an object that behaves as expected:
var functionObject = {
name: 'functionObject',
printName: function() {
console.log(this);
}
};
// Outputs: Object {name: "functionObject"}
functionObject.printName();
As per observations in the Babel REPL, it appears they are transpiled like so:
var arrowObject = {
name: 'arrowObject',
printName: function printName() {
console.log(undefined);
}
};
This contrasts with:
var functionObject = {
name: 'functionObject',
printName: function printName() {
console.log(this);
}
};
The question remains: Why does arrowObject.printName();
not have arrowObject
as the value of this
?
Logs were generated using Fiddle (with no use strict;
directive).