Friday, March 8, 2019

Javascript: Arrow functions and this

Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:

(a, b) => a + b // implicitly returning a + b

(a, b) => {                // explicitly returning a + b
   return a + b;
}

a => a * a                // omit () when there is one parameter

() => 2                   // () mandatory when there are no parameters

(a, b) => {               // explicitly returning JS object
   return {
      a1: a, b1: b
   }
}

(a, b) => ({              // implicitly returning JS object
   a1: a, b1: b
})

An arrow function does not have its own this. this in arrow functions is always statically defined by the surrounding lexical scope.
In the example below, when using traditional function, this refers to the num object, whereas when using arrow notation, this is pointing to the global object. Arrow functions doesn't have its own this, and so this refers to outer scope, and outer scope for num object is the window object.


Even if I use call() method, result is the same.


In the below example, when using traditional function, this refers to the global object, whereas using arrow function, we get the desired result.


In order to get the greeting message using the traditional function, there are several ways to keep reference to this object inside of setTimeOut function. You can create a self variable like below:

const str = {
    value: 'Delayed greeting',
    greet: function() {
        const self = this;
        setTimeout(function() {
            console.log(self.value);
        }, 2000)
    }
};

str.greet();

or bind with this like below:

const str = {
    value: "Delayed greeting",
    greet: function() {
        setTimeout(
            function() {
                console.log(this.value);
            }.bind(this),
            2000
        );
    }
};

str.greet();

It is not possible to use arrow function expression as a function constructor and create new objects from it.
Share This:    Facebook Twitter

0 comments:

Post a Comment

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top