Home » Programming » Javascript » Javascript This

What is the ‘this’ Keyword in JavaScript (Object-Oriented Programming)

The ‘this‘ keyword in JavaScript is a confusing concept for some – the meaning of ‘this‘ changes based on context.  This article explains what ‘this‘ is.

What is Object-Oriented Programming

Object-Oriented Programming is a way of structuring your code so that data is organized into objectsJavaScript supports Object-Oriented programming and provides various tools to help implement it.

Put simply, rather than having a bunch of separate abstract variables describing an item, you combine them into a single object which represents that item. You can also add functions to the object to make it do things, like updating values stored in the object or interacting with other objects.

For example, if you are building an app that records all of the cars you have ever owned, rather than having separate variables holding all of the makes, models, colors, etc., for each car, you have a car object which holds the data for a single car. This makes it easy to handle large amounts of data and makes your application easier to structure. If you want to get all of the information for a certain car, you can grab that object and know it contains everything you need to know about that specific item.

Scopes and Contexts

While often used interchangeably, scopes and contexts are slightly different.

scope defines variable access – whether a variable is accessible to the code in the current part of the application. For example, a variable declared inside a function is not accessible outside of it as they are different scopes.

context, however, is the parent object of the code being run. As an object can contain multiple methods (which are functions), each method will have a different scope (the functions themselves) with the same context (the parent object).

See more on variables and scopes here.

So What is this?

this is a keyword in JavaScript. It is used as you would use any variable.

this refers to this object you are working in, right now, where this is written in the code. That is, it refers to the current context.

If you are working in a functionthis refers to the parent object of the function. If you are working in an objectthis refers to the object.

JavaScript treats many things as objects, so here’s a rundown of what this refers to in each scenario.

this Outside of Methods, Functions, Objects

If this is used on its own, outside of any parent class, object, function, it refers to the global object.

var testVar = 9;
console.log(this.testVar); // Prints 9

Above, a global variable testVar is defined. To prove that this refers to the global object, you can try to access this.testVar – which returns 9.

this in a Method (Object Method Binding)

Objects in JavaScript are of different classes. Classes can have methods – functions that can be executed on each object of the given class to do things with it.

When writing code for a method, this will always refer to object.

For example:

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }
}

var fordCar = new Car('Ford', 'Model T');

Above, a Car class is defined. Objects can then be created with this class. The constructor method (a function) is used for setting the values of the Car class when it is created set attributes for the variable this.

In this case, an object named fordCar is created. When the constructor is run, this refers to the fordCar object and sets the make/model values for it that were passed as parameters.

Explicit Function Binding

It is possible to change what this refers to inside an object method by using the call() and apply() methods of that object. call() and apply() are built-in JavaScript methods that are available to all objects of any class. Both methods work similarly and differ in how additional arguments are passed to them after the context has been provided.

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }

    // makeModel method will return the make of model of the current object
    makeModel(){
        return this.make + ' ' + this.model;
    }
}

var fordCar = new Car('Ford', 'Model T');
var toyotaCar = new Car('Toyota', 'Hilux');

fordCar.makeModel.call(toyotaCar);  // Will return "Toyota Hilux" - even though it was called from the fordCar model, as the call method changed the context
fordCar.makeModel.apply(toyotaCar);  // Will return "Toyota Hilux" - even though it was called from the fordCar model, as the apply method changed the context

this in a Function

As explained above, functions have scopes but do not provide a context. So, inside a standalone function with no parent object or class, this will refer to the global context.

var testVar = 9;

function testFunction(){
    console.log(this.testVar); // Prints 9
}

testFunction(); // Run the function defined above

Functions and Strict Mode

Strict Mode is an optional setting that can be enabled in JavaScript, which restricts you from doing some things that you usually can do. These things tend to either be things that will be removed from future revisions of JavaScript or things that are considered “sloppy” – code that is valid but written in a way that is likely to cause errors or be hard to interpret.

So, in strict mode, this does NOT refer to the global object when used in a standalone function. It doesn’t refer to anything and will return undefined.

'use strict';

var testVar = 9;

function testFunction(){
    console.log(this.testVar); // undefined
}

testFunction(); // Run the function defined above

this in HTML Event Handlers

When this is called from within an event handler in an HTML element, it refers to the HTML element itself.

<button onclick="console.log(this);">
    Print information on this HTML element
</button>

The above HTML code will print information on the <button> HTML element to the JavaScript console.

that = this; – What the?

Sometimes you’ll encounter the following code:

var that = this;

The coder is assigning the current value of this to a new variable called that.

They’re doing this because the context is about to change (and with it, the value of this)- but they want to retain access to the current value of this.

If the scope isn’t changing, assigning this to a new variable allows you to keep accessing the previous context via the newly created variable (named that here, but you can call it whatever you want).

 

Still have questions? Here’s the link to Mozilla’s resource on this.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment