JavaScript Tutorial Series - this

Understanding the this concept is essential to learning JavaScript. this is a reserved word which refers to the current scope. Scope changes based on the current context in the code. For example, inside a class, this is used to access methods and variables defined in the class.


class Year {
	constructor(key) {
        this.year = 2020;
    }
    
    printYear(y=this.year) {
    	console.log('The year is: ' + y);
    }
    
    
    nextYear() {    	
        this.printYear(this.year + 1);
    }
}


const theYear = new Year();
theYear.printYear();
theYear.nextYear();

Scope gets tricky when using things like event handlers inside a class. The scope inside a method is the containing class. The scope inside an event handler inside a method is the element receiving the event. The problem occurs when you want to access something from the class the method is in, inside the event handler. In order to use a method or variable from the class inside the event handler, a variable outside the event handler that points at this, will need to be created. That variable can then be used inside the event handler to access a class method or variable. For example:




  
    This Example
  

  
    

    
  



To see the difference in this scope, copy the above to an html file and load it in the browser. Open the console and change the year value. In the code, try changing _this.printYear() to this.printYear(), reload the html file, change the year value and see what happens. Changing to this.printYear(), calls a function called printYear belonging to the input dom element, which doesn't exist, so an error is thrown. When in doubt, create a variable pointing to the outer scope you need to access and use that inside the containing scope instead of using this when its' scope is uncertain. (#sponsored)

More JavaScript




Comments