Difference between Arrow Function and Regular Function — in the context of “this”
when it come to the concept of “this” in the Functions it create some confusion to me in terms of how it is different when it used within the Arrow Function and when it used within the Regular Function.
So in this article I am going to share some of the differences of the Arrow and Regular functions in terms of “this” which I observed and understand.
Regular Function’s execution context is different so the behavior of “this ” depend upon how it called.
for example if a function fun1() is invoking normally then the value of this will point to the window but if the fun1() will execute through an object’s method like Obj.fun1() then the value of this will point to the owner of that function which is Obj in this case.
It will be more clear from the following example.
In the above example fun1() is referring to window and Obj.fun1() is referring to Obj.
But when it come to the Arrow function then it is differ from the Regular function.
The value of “this ” in the Arrow Function is depend upon its outer function.
In this example we can see that how the behavior of “this” is different for Arrow function.
the innerArrowFn() is defined within the normalFn() so its “this” is pointing to the “this” of normalFn().
and in the another case of outerArrowFn(), it is pointing to window’s “this”.