Weird! 'this' keyword appears not working in regular function(response){..}
Last month I was working on some requirement, where I was calling a regular function(response) {..} inside a callback method. It was weird for me that the scope variables were appearing as undefined every time I logged them.
connectedCallback(){
const messageCallback =function(response){
this.lead = response.data.sobject;
this.leadName= this.lead.Name; //undefined
this.leadStatus = this.lead.Status; //undefined
const dispatchLeads = new CustomEvent('openutilitybar');
this.dispatchEvent(dispatchLeads);
};
I tried to understand the scope of 'this' in a regular function(response){..}. After checking few community references and Mozilla Developer Guide, I found that regular functions have their own 'this' scope i.e this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
To solve the issue, ES6 and the later versions have come up with Arrow functions i.e (response)=>{..}. Unlike regular functions, arrow functions do not have their own 'this'. The value of 'this' inside an arrow function remains the same throughout the life cycle of the function and is always bound to the value of this in the closest non-arrow parent function.
connectedCallback(){
const messageCallback = (response)=>{
this.lead = response.data.sobject;
this.leadName= this.lead.Name; //Smith
this.leadStatus = this.lead.Status; //Open - Not Contacted
const dispatchLeads = new CustomEvent('openutilitybar');
this.dispatchEvent(dispatchLeads);
};
References:
No comments:
Post a Comment