- What is “this” in JavaScript?
- Global Context
- Function context
- Object Method Context
- “this” with a getter or setter
- Constructor Context
- DOM event handler Context
- Summary
- The JavaScript this Keyword
- Note
- this in a Method
- this Alone
- Example
- Example
- this in a Function (Default)
- Example
- this in a Function (Strict)
- Example
- this in Event Handlers
- Example
- Object Method Binding
- Example
- Example
- Explicit Function Binding
- See Also:
- Example
- Function Borrowing
- Example
- This Precedence
What is “this” in JavaScript?
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
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.
If you are looking to master JavaScript, I highly recommend Mosh’s courses on JavaScript. The link below has several JS courses by Mosh.
Hope you enjoyed this article!
The JavaScript this Keyword
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined . |
In an event, this refers to the element that received the event. |
Methods like call() , apply() , and bind() can refer this to any object. |
Note
this in a Method
When used in an object method, this refers to the object.
In the example on top of this page, this refers to the person object.
Because the fullName method is a method of the person object.
this Alone
When used alone, this refers to the global object.
Because this is running in the global scope.
In a browser window the global object is [object Window] :
Example
In strict mode, when used alone, this also refers to the global object:
Example
this in a Function (Default)
In a function, the global object is the default binding for this .
In a browser window the global object is [object Window] :
Example
this in a Function (Strict)
JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined .
Example
this in Event Handlers
In HTML event handlers, this refers to the HTML element that received the event:
Example
Object Method Binding
In these examples, this is the person object:
Example
const person = firstName : «John»,
lastName : «Doe»,
id : 5566,
myFunction : function() return this;
>
>;
Example
const person = firstName: «John»,
lastName : «Doe»,
id : 5566,
fullName : function() return this.firstName + » » + this.lastName;
>
>;
i.e. this.firstName is the firstName property of this (the person object).
Explicit Function Binding
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as argument.
See Also:
The example below calls person1.fullName with person2 as an argument, this refers to person2, even if fullName is a method of person1:
Example
const person1 = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person2 = firstName:»John»,
lastName: «Doe»,
>
// Return «John Doe»:
person1.fullName.call(person2);
Function Borrowing
With the bind() method, an object can borrow a method from another object.
This example creates 2 objects (person and member).
The member object borrows the fullname method from the person object:
Example
const person = <
firstName:»John»,
lastName: «Doe»,
fullName: function () <
return this.firstName + » » + this.lastName;
>
>
const member = firstName:»Hege»,
lastName: «Nilsen»,
>
let fullName = person.fullName.bind(member);
This Precedence
To determine which object this refers to; use the following precedence of order.
Precedence | Object |
1 | bind() |
2 | apply() and call() |
3 | Object method |
4 | Global scope |
Is this in a function being called using bind()?
Is this in a function being called using apply()?
Is this in a function being called using call()?
Is this in an object function (method)?
Is this in a function in the global scope.