Understanding of this variable in JavaScript requires very basic knowledge of JavaScript. this keyword defines an object, that object which is executing the current bit of JavaScript code. In JavaScript, “this” variable is a variable that every execution context gets, in a regular function call. Every JavaScript function has a reference to its current execution context while executing, called this. Execution context means here means the manner of calling of functions.

We can understand this variable by knowing how, when and from an instance calls the function or variable. This is irrespective of where someone defines the function or variables.

var test = {
   number: 5,
   testFunction : function() {
      return this.number;
   },
};
console.log(test. testFunction ());
// expected output: 5

Here, the way of calling the function determines the value of this variable. It can’t be set by assignment during execution. It may be different each time the function is called. ES5 JavaScript coding format introduces the bind() method to set the value of a function’s this regardless of how it’s call, and ES6 JavaScript coding format introduces arrow functions which don’t provide their own this binding.

Global Context

The following example provides the understanding of this variable in JavaScript in a global context :

function namePerson() {
    console.log(this.name);
}
var name = "Doug";
var obj1 = { name: "Buggati", cars: cars};
var obj2 = { name: "Lamborgini", cars :cars};
namePerson();     // "Doug"
obj1.cars();      // "Buggati"
obj2.cars();      // "Lamborgini"

In the above code snippet, the job of namePerson() function is printing this.name. It means it’s trying to print the value of name property of the current execution context(i.e. this object).

Above code snippet, calling of function namePerson() prints “Doug”. Because the context of execution is not specified so by default its global context. There is a variable name is present at global context whose value is “Doug”.

Calling of obj1.cars() prints “Buggati”. The reason behind this is it calls function cars() with the execution context as obj1 so this.name becomes obj1.name . Same with obj2.cars() call where the execution context of function **cars()**is obj2.

The “this” variable points at the global object or the window in the browser, which is the default. In a method call, which is a function within a variable, the “this” variable points at the method calling the object. The function call sets the value of **this**variable.

Function context

Inside a function, the value of this dependent on the calling of function.

The following example provides the understanding of this variable in JavaScript in Function or method context :

function f1() {
   return this;
}
// In a browser:
f1() === window;
// true  // In Node:
f1() === global; // true

In strict mode, when entering the execution context sets the value of this. So, in the following case, **this**will default to undefined:

function f2() {
'use strict';
// see strict mode  return this;
}
f2() === undefined; // true

So, in strict mode, if the execution context does not define this, it remains undefined.

Object Method Context

When a function is called as a method of an object, it’s this is set to the object the method is called on.

During invoking of number.varMethod() inside the function, this is bound to the number object.

The following example provides the understanding of this variable in JavaScript in Object context :

var number = {
    variable: 003,
    varMethod: function() {
        return this.variable;
    }
};
console.log(number.varMethod());
// prints: 003

Here, we have an object called number. The object has a variable and method denoted by variable assigned as “003” and method varMethod which returns the variable. Now calling of _number.varMethod( ) _ prints “003”. Here, an Object can be assigned any variable or function. Using object name, you can call its variables and instances.

this” with a getter or setter

A function used has its this bound to the object from which the property is being set or gotten.

The following example provides the understanding of this variable in JavaScript using getters and setters :

function sum() {
      return this.x + this.y + this.z;
}
var maths = {
    x: 1,  y: 2,  z: 3,
get mean() {
    return (this.x + this.y + this.z) / 3;
}
};
Object.defineProperty(maths, 'sum', {
   get: sum,
   enumerable: true,
   configurable: true
});
console.log(maths.mean, maths.sum); // 2, 6

Constructor Context

The constructor is a function that is called immediately when a project is run.

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

The following example provides the understanding of this variable in JavaScript in constructor context :

function varX() {
   this.x = 003;
}
var number = new varX();
console.log(number.x); // 003
    function varY() {
      this.y = 003;
    return { y: 0003 };
    }
var number2 = new varY();
console.log(number2.y); // 0003

Here, Constructor is denoted my function _varX( ). _ The instance of the constructor is called using number variable which when prints “003” when called as number.x. Same goes for second constructor function varY( ).

DOM event handler Context

When a function is used as an event handler, its this is set to the element the event fired from.

The following example provides the understanding of this variable in JavaScript in event handlers :

// When called as a listener, turns the related element black
function turnBlack(event){ 
    // Always true  console.log(this === event.currentTarget);
    // true when currentTarget and target are the same object s
    console.log(this === event.target);
    this.style.backgroundColor = '#000000’;
}
    // Get a list of every element in the document
    var elements = document.getElementsByTagName('*');
    // Add turn Black as a click listener so when the// element is clicked on, it turns Black
for (var i = 0; i < elements.length; i++){
    elements[i].addEventListener('click', turnBlack, false);
}

Summary

Numerous JavaScript Frameworks available today use this variable differently. AngularJS, Vue, ReactJS, Angular Frameworks and so on. The style of use may be different in different frameworks but the functionality is the same. The most basic understanding of this variable is that it allows you to access the variables and methods declared globally or locally anywhere inside the scope. It also allows calls of different external modules/plugins in a particular scope. Its use is very simple and efficient which is essential in case of learning JavaScript.

#javascript #web-development

What is “this” in JavaScript?
21.75 GEEK