The question is directed at people who have thought about code style in the context of the upcoming ECMAScript 6 (Harmony) and who have already worked with the language.
In a simple way,
var a =20; function a(){this.a=10; console.log(a);}
//20, since the context here is window.
Another instance:
var a = 20;
function ex(){
this.a = 10;
function inner(){
console.log(this.a); //can you guess the output of this line.
}
inner();
}
var test = new ex();
Ans: The console would print 20.
The reason being whenever a function is executed its own stack is created, in this example ex
function is executed with the new
operator so a context will be created, and when inner
is executed it JS would create a new stack and execute the inner
function a global context
though there is a local context.
So, if we want inner
function to have a local context which is ex
then we need to bind the context to inner function.
Arrows solve this problem, instead of taking the Global context
they take the local context
if exists any. In the given example,
it will take new ex()
as this
.
So, in all cases where binding is explicit Arrows solve the problem by defaults.