ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Arrow function
    DynamicPL/Javascript 2019. 10. 24. 17:43

    1. Overview

    Arrow functions which are added in ES6 are so simple and share the surrounding this keyword. Unlike normal function, arrow functions don't get their own "this" keyword.

    2. Description

    2.1 Expression

    const years = [1990, 1965, 1982, 1937];
    
    // ES5
    var ages5 = years.map(function(el) {
        return 2016 - el;
    });
    console.log(ages5);
    
    
    // ES6
    // a lots less code
    let ages6 = years.map(el => 2016 - el);
    console.log(ages6);
    
    ages6 = years.map((el, index) => `Age element ${index + 1}: ${2016 - el}.`);
    console.log(ages6);
    
    ages6 = years.map((el, index) => {
        const now = new Date().getFullYear();
        const age = now - el;
        return `Age element ${index + 1}: ${age}.`
    });
    console.log(ages6);

    2.2 Lexical this keyword in an arrow function

    // ES5
    var box5 = {
        color: 'green',
        position: 1,
        clickMe: function() {
        
        	/*
            in this statement, this points global object, which is window object.
            Because this callback function is not method, but regular function call.
        	document.querySelector('.green').addEventListener('click', function() {
                var str = 'This is box number ' + this.position + ' and it is ' + this.color;
                alert(str);
            });
           */
           // this approach retains box5's this to be used in callback function
           var self = this; 
           document.querySelector('.green').addEventListener('click', function() {
                var str = 'This is box number ' + self.position + ' and it is ' + self.color;
                alert(str);
            });
        }
    }
    //box5.clickMe();
    
    
    // ES6
    const box6 = {
        color: 'green',
        position: 1,
        clickMe: function() {
            document.querySelector('.green').addEventListener('click', () => {
                var str = 'This is box number ' + this.position + ' and it is ' + this.color;
                alert(str);
            });
        }
    }
    box6.clickMe();
    
    
    const box66 = {
        color: 'green',
        position: 1,
        // in arrow function, this is from surrounding function because arrow function shares this from its surronding.
        // so in this case, clickMe's this keyword share the surrounding this which is window object.
        clickMe: () => {
            document.querySelector('.green').addEventListener('click', () => {
                var str = 'This is box number ' + this.position + ' and it is ' + this.color;
                alert(str);
            });
        }
    }
    box66.clickMe();
    
    
    function Person(name) {
        this.name = name;
    }
    
    // ES5
    Person.prototype.myFriends5 = function(friends) {
    
    	var arr = friends.map(function(el) {
           // this is another function which is anonymous function. 
           // in this function, this points global object so this.name is undefined.
           return this.name + ' is friends with ' + el; 
        });
        
        var arr = friends.map(function(el) {
           return this.name + ' is friends with ' + el; 
        // bind can define the "this" keyword manually and create a copy of this function
        // while call actually immediately.
        }.bind(this));
        
        console.log(arr);
    }
    
    var friends = ['Bob', 'Jane', 'Mark'];
    new Person('John').myFriends5(friends);
    
    
    // ES6
    Person.prototype.myFriends6 = function(friends) {
    	// this point Person object which is shared with arrow function.
        var arr = friends.map(el => `${this.name} is friends with ${el}`);
    
        console.log(arr);
    }
    
    new Person('Mike').myFriends6(friends);

    2.2.1 this in normal function

    The "this" keyword actually points to that object in Only the method call But in a regular function call, the "this" keyword will always point to the global object. In the above clickMe function, the only clickMe is method but not callback function inside of it. So inside of callback function, this points window object because it's a regular function call.

    2.2.2 this in Arrow function

    Unlike normal function, arrow functions don't get their own "this" keyword but share this keyword from its surroundings. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

    let me = { 
     name: "Ashutosh Verma", 
     thisInArrow:() => { 
     console.log("My name is " + this.name); // no 'this' binding here 
     }, 
     thisInRegular(){ 
     console.log("My name is " + this.name); // 'this' binding works here 
     } 
    };
    me.thisInArrow(); 
    me.thisInRegular();

    2.3 Using new keyword

    Regular functions created using function declarations or expressions are ‘constructible’ and ‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible.

    let add = function(x, y) {console.log(`x + y is ${x+y}`)};
    new add(2,3); // x + y is 5
    
    let add = (x, y) => console.log(x + y);
    new add(2,3); // TypeError: add is not a constructor

    3. References

    https://codingheroes.io/

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    https://www.tutorialspoint.com/difference-between-regular-functions-and-arrow-functions-in-javascript

    https://www.geeksforgeeks.org/difference-between-regular-functions-and-arrow-functions/

    댓글

Designed by Tistory.