I was recently going learning about the this keyword and how it is affected by normal functions function() {...} vs arrow functions ()=>{...}. However, these functions are defined within member functions of a class definition:
// Case 1
// filename = index.js
class myClass{
myString = undefined;
myNumber = undefined;
constructor(aString, aNumber){
this.myString = aString;
this.myNumber = aNumber;
}
logThisWithRegularFunc(){
let logger = function(){
console.log(this); // Console output = undefined, because function(){} created a new scope/definition for 'this'
}
return logger();
}
logThisWithArrowFunc(){
let logger = ()=>{
console.log(this); // Console output = myClass { myString: [someString], myNumber: [someNumber] }
}
return logger();
}
}
let dumiObj = new myClass("Hello", 200);
dumiObj.logThisWithRegularFunc();
dumiObj.logThisWithArrowFunc();
The console output is as expected:
$ node index.js
undefined
myClass { myString: 'Hello', myNumber: 200 }
$
However, if I create the same two functions outside of a class as follows:
// Case 2
// filename = index.js
// Regular functions
function logThisWithRegularFunc(){
this.someInternalString = "Hello Internal String 1";
console.log(Object.keys(this));
}
// Arrow Function
let logThisWithArrowFunc = ()=>{
this.someInternalString = "Hello Internal String 1";
console.log(Object.keys(this));
}
logThisWithRegularFunc();
logThisWithArrowFunc();
I get the following output:
$ node index.js
<ref *1> Object [global] {
global: [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
},
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
},
someInternalString: 'Hello Internal String 1'
}
{ someInternalString: 'Hello Internal String 1' }
$
What could be the reason for this? How are the two cases different? How can the behavior of these two functions be justified in these two cases?
P.S. Thanks in advance! :-)