‘this’ Variable in LWC

"this" variable

Please complete our LWC tutorial series Part 3 : Button Click in LWC

So far in our tutorials, we have learned how to provide button click in our component. But before jumping further, we will make sure to learn about ‘this’ variable in LWC.

As this is both interesting and haunting topic of JS, which will also be used extensively in our LWC framework coding. Let’s get started 

Google says: ‘THIS’ is the person, thing, or idea that is present in the place, time, or that has just been mentioned (Pronouns). 

Example : This is the mozzarella pizza.

JS says: ‘THIS’ refers to an object i.e. subject in context or subject of the executing code.

Example to name and display a pizza in js.

var pizza = {
    name        : 'mozzarella',
    actiontoeat : function(){
        console.log(this.name);
        // 'this.name' is actually 'pizza.name'
        // 'this' refers to 'owner' of function
    }
}

So in both of the above cases, ‘THIS‘ refers to our Pizza. We use ‘this’ similar to the way we use pronouns in natural language. 

Example:  (1) – ‘ Alex is a better coder because he practices a lot.’ 
                  (2) – ‘ Alex is a better coder because Alex practices a lot.’

(1) In this sentence, we are sure that there is only one Alex, and he is a better coder. 

(2) In the second sentence, there might be two different Alex which makes unsure which Alex is a better code. 

We used ‘he’ to remove ambiguity. Same way, we could have used the ‘pizza’ object again but to remove ambiguity, we used ‘this’.

How this is a better practice?

1. Consider that there could be another global variable with the same name as “pizza”. Then “pizza.name” could attempt to access the name from the global pizza object.
2. It helps to makes our code less ambiguous (debatable).
3. It tells us that we are referring to the very specific pizza.

NOTE: “this” keyword not only refers to the object but it also contains the value of the object.

So far we have seen that we can use ‘this’ keyword
      1. as a shortcut
      2. as a referent
      3. It refers to an object i.e. subject in context or the subject of the executing code.

This is like an imposter, it takes different values depending on where it is used.

‘This’ is an imposter, just like Skrull in MCU.

Let’s pick examples to look over the possibilities for ‘this’ variable.

  1. In a function, ‘this’ refers to global object.
<lightning-button onclick={functionClick} label="Click Me">
</lightning-button>
 functionClick(){
    this.thisFunction();
 }
 
 thisFunction(){
    console.log('Inner HTML @@@ - ' +this.template.innerHTML);
    // prints inner HTML
    console.log(this);  
    // prints global object    
 }

   2. In a method, ‘this’ refers to owner object.

<lightning-button onclick={MethodClick} label="Click Me">
</lightning-button>
MethodClick(){
    this.thisObject.firstmethod();
}
 
thisObject = {
    firstproperty: "MyFirstProperty",
    firstmethod(){
        console.log(this.firstproperty);
        // prints MyFirstProperty
        console.log(this);
        // prints thisObject
    }
}

   3. Object Array iteration

We use forEach with callback function to iterate array. Inside Callback function this reference to window object and not to current object.
So we pass this as second argument to callback function to refer the current object.

<lightning-button onclick={arrayClick} label="Click Me">
</lightning-button>
arrayClick(){
    this.thisArrayObject.runArray();
}
 
thisArrayObject = {
    NameOfObject: "Array Object",
    Array:['a','b','c'],
    runArray(){
        this.Array.forEach(function(arr){
            console.log(arr);
            console.log(this.NameOfObject);
        }, this);
    }
}

self is being used to maintain a reference to the original this even as the context is changing.

Functions, in particular, create a new ‘this’ and so when you want to keep a reference to an “outer” object you sometimes see the pattern:

var self = this; 

var self = this;
return function(whatever) {
  return self.foo(whatever); // `this` here is for the inner function
}

Make sure to comment down below your reviews.

Till then,
Thanks for reading! & PEACE

(Visited 1,111 times, 1 visits today)

Leave a Reply