I'm trying to figure out why an arrow function in an object literal is called with window as this. Can someone give me some insight?
var arrowObject = {
name: 'arrowObject',
printName: () => {
console.log(this);
}
};
// Prints: Window {external: Object, chrome: Object ...}
arrowObject.printName();
And an object that works as expected:
var functionObject = {
name: 'functionObject',
printName: function() {
console.log(this);
}
};
// Prints: Object {name: "functionObject"}
functionObject.printName();
According to Babel REPL, they're transpiled to
var arrowObject = {
name: 'arrowObject',
printName: function printName() {
console.log(undefined);
}
};
And
var functionObject = {
name: 'functionObject',
printName: function printName() {
console.log(this);
}
};
Why isn't arrowObject.printName(); called with arrowObject as this?
Console logs are from Fiddle (where use strict; isn't used).