in code snippet below:
in 1st case with arrow function - object logged
in 2nd case with function declaration - window logged
how and why does the arrow function preserve the context?
// 1ST CASE
function A() {
this.getThis = () => {
console.log(this)
}
}
const a = new A
const aa = a.getThis
/* same as:
const aa = () => {
console.log(this)
}
*/
aa() // object, context preserved O_o
// 2ND CASE
function B() {
this.getThis = function() {
console.log(this)
}
}
const b = new B
// b.getThis() // will log object
const bb = b.getThis
/* same as:
const bb = function() {
console.log(this)
}
*/
bb() // window