Node.js Node.js v6 New Features and Improvement "this" in Arrow Function


this in function refers to instance object used to call that function but this in arrow function is equal to this of function in which arrow function is defined.

Let's understand using diagramlexical scope of this in arrow function

Understanding using examples.

var normalFn = function(){
   console.log(this) // refers to global/window object.

var arrowFn = () => console.log(this); // refers to window or global object as function is defined in scope of global/window object
var service = {

    constructorFn : function(){

        console.log(this); //  refers to service as service object used to call method.

        var nestedFn = function(){
            console.log(this); // refers window or global object because no instance object was used to call this method.
    arrowFn : function(){
        console.log(this); // refers to service as service object was used to call method.
        let fn = () => console.log(this); // refers to service object as arrow function defined in function which is called using instance object.

// calling defined functions

In arrow function, this is lexical scope which is the scope of function where arrow function is defined.
The first example is the traditional way of defining functions and hence, this refers to global/window object.
In the second example this is used inside arrow function hence this refers to the scope where it is defined(which is windows or global object). In the third example this is service object as service object is used to call the function.
In fourth example, arrow function in defined and called from the function whose scope is service, hence it prints service object.

Note: - global object is printed in Node.Js and windows object in browser.