When should I use Arrow functions in ECMAScript 6?

后端 未结 9 1622
滥情空心
滥情空心 2020-11-21 05:53

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.

9条回答
  •  爱一瞬间的悲伤
    2020-11-21 06:11

    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.

提交回复
热议问题