JavaScript “This” Keyword and How to Implement It

JavaScript—the most widely used web programming language—is an open-source tool designed for creating web-based applications. It is lightweight and interpreted, which makes it perform much faster than other languages. Because JavaScript is integrated with HTML, it is also easier to implement in web applications. 

Master Core Java 8 Concepts, Java Servlet & More!

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet & More!

In this article, we will cover all of the basics you need to know about JavaScript “this” keyword. We will also introduce the concept of reference. This article will also acquaint you with the “this” keyword on a global and local scope. 

JavaScript is essential for web development, and if you’re contemplating a career in this industry, it’s important to know this widely-used programming language. 

What is “This” Keyword in Javascript?

this-js

Fig: JavaScript “this” keyword

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object. If the function that is being referenced is a method in an object, “this” references the object itself.

The JavaScript “this” keyword is one of the most widely used keywords. It can seem complex at first, but once you start using “this” keyword, everything will become clear.

Also Read: An Introduction to JavaScript: Here Is All You Need to Know

JavaScript Background

Typically, when individuals show an interest in web development, they learn the basics with HTML and CSS. From there, they move on to JavaScript. These three elements together form the backbone of web development.

  • HTML is your page's structure which includes the headers, the body text, and any images you want to include. It defines the contents of a web page.
  • CSS controls how that page looks (it's what you'll use to customize fonts, background colors, and so on).
  • JavaScript is the third element. Once you've created your structure (HTML) and your aesthetic vibe (CSS), JavaScript makes your site dynamic (automatically updateable).

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Global Scope

If you call a function from the global scope that includes “this” keyword, then “this” will always point to the window object. The following example can help to visualize this concept: 

<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <title>JavaScript This Keyword</title>  </head>  <body>    <script>      var myVar = 100;      function printMe() {        var myVar = 200;        alert("myVar = " + myVar); // 200        alert("this.myVar = " + this.myVar); // 100      }      printMe();    </script>  </body></html>
  • We declare a variable myVar with an initial value of 100
  • After that, we define a function that sends an alert with a statement to the browser window when it is called
  • Whenever we access the value of myVar without “this” keyword, it gets the value defined locally within that function
  • On the other hand, when we try to get the value of myVar variable using the “this” keyword, it fetches the value defined outside the function (globally)

Object Method

In JavaScript, we can create objects of a function using the new keyword. Therefore, whenever we create an object of a function using the new keyword, then “this” will point to that particular object. We can take a look at this in more detail with the following example:

<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <title>JavaScript This Keyword</title>  </head>  <body>    <script>      var myVar = 100;      function printMe() {        this.myVar = 200;        this.display = function () {          var myVar = 300;          alert("myVar = " + myVar); // 300          alert("this.myVar = " + this.myVar); // 200        };      }      var obj = new printMe();      obj.display();    </script>  </body></html>
  • We declare a variable myVar and initialize it with a value of 100
  • Now, when we create an object ‘obj’, it will have two properties that we defined in the code: ‘myVar’ and ‘display’—note that display is a function expression in this case
  • Therefore, “this” keyword inside the display() method of the object ‘obj’ points to the value outside the scope of the display() method
  • When we call the display() method, it initially shows the alert with the local value, and then an additional alert with the global value fetched using “this” keyword

While HTML and CSS are required to code a basic web page, JavaScript is the language that will help you bring that page to life, making it more appealing to your audience. It is the key to making your website look and feel more like a full-fledged application.

Taking the time to learn JavaScript will help you immensely in the web development world and can make you a qualified candidate for an exciting role as a web developer.

Also Read: Top 10 Reasons to Learn JavaScript

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Types of Bindings in JavaScript

There are different types of bindings in JavaScript. They are described in the below sections:

1. Default Binding

In this type of binding, this keyword refers to a global object. This is applied in case of standalone functions. If the mode is set to strict, then this keyword refers to undefined.

function warn() {   //function is definedconsole.log(this.name + ‘warned Ramesh yesterday’);}const name = ‘Suresh’;warn(); //function is called

2. Implicit Binding

This is applied when you call a function using an object and a dot symbol. In this situation, this keyword points out to the object used to call the function. 

function Hemanth(){   //function is definedconsole.log(this)}const obj1 = {randomKeyValue : 1735,Hemanth : Hemanth,}obj1.Hemanth();   //function is called using obj1

3. Explicit Binding

This binding is used when one needs to pressurize the function to use a particular object as its context. It can be achieved using two methods call() and apply(). This is also known as hard binding sometimes.

function warn() {console.log('My name is  '+ this.name);}const obj1 = {name : 'Hemanth',}warn.call(obj1);

4. Constructor Call Binding

When a constructor is calledin the code or when a function is called with a ‘new’ keyword before it, then certain things can happenn:

  1. Creationf of new object
  2. The newly createdobject is linked to the function created it by calling
  3. The constructed object is set as ‘this’ binding to that function call.
function myName(name) {    this.name = name; } const obj1 = new myName('Hemanth'); console.log(obj1.name);

Dive Deep Into Java Core Concepts

Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

Global Context

In JavaScript, in the concept of global concept this keyword refers to some global object. Window object on teh browser and global object in Node.js, so window object is returned when this is typed.

console.log(this === window); 

Function Context

There are several methods to call a function in JavaScript. The behavior of this changes from one context to another. Some of the variations are discussed below:

1. Simple Function Invocation

When a function is called in non-strict mode, this refers to the global object which is a window in the browser and global on Node.js. Whereas in strict mode, the JavaScript sets this to undefined mode. Strict mode can be enabled using some directives such as ‘use strict’. It applies to both function and nested functions.

2. Method Invocation

When a method is called using an object JavaScript sets this to the object of that method. 

let food = {     cuisine: 'Asian',     getFood: function () {         return this.cuisine;     }}console.log(food.getFood());

In the above example, this object in the getFood() method refers to a food object.

3. Constructor Invocation

We use the function as a constructor, when a new keyword is used to create an instance of a function object.

function Food(cuisine) {    this.cuisine = cuisine;}Food.prototype.getCuisine = function () {return this.cuisine;}let rice = new Food('Asian');console.log(rice.getCuisine());

The expression new Food(‘Asian’) is a constructor invocation of the Food function.

4. Indirect Invocation

In JavaScript, functions are objects and are instances of Function Type which has two methods call() and apply(). These two methods are used to set this value when a function is called. 

function getCusisine(prefix) {     console.log(prefix + this.type);}let rice = {    type: 'Rice'};let Noodles = {    type: 'Noodles'};getCusisine.call(Noodles, "It's  ");getCusisine.call(rice, "It's  ");

In the above example, we called getCusisine() function indirectly using call() method of getCusisine function. Later we passed two parameters, Noodles and rice as the first argument to call(). The apply() is similar to call() where the second parameter is an array of arguments.

Unleash Your Career as a Full Stack Developer!

Full Stack Developer - MERN StackEXPLORE COURSE
Unleash Your Career as a Full Stack Developer!

Arrow Functions

Arrow functions were introduced in the ES6 version of JavaScript. When compared to the regular functions, it allows the developers to write functions more cleanly. It doesn't create its execution content but inherits this from the outer function where the arrow function is defined. The syntax of using an arrow function is defined here:

let someFunction = (arg1, arg2,..., argN) => {statements;}

Let's look at an arrow function that takes no argument. Whenever there is no input argument to the arrow function, we must use open and close parentheses. 

let wish = () => console.log(‘Good Afternoon’);wish();

Call(), Apply(), and Bind()

The call(), apply() and bind() methods are in-buit functions in JavaScript. 

The call() method in JavaScript is used to invoke a function. 

function firstProgram() {    console.log('Hello world');}firstProgram();firstProgram.call();

In the above program, both the statements firstProgram() and firstProgram.call() invokes the method firstProgram() and prints Hello World. Similarly, apply() is also used to invoke the function. These are used to set the context of this. 

The bind() is used to call a function with this value. It also allows the setting which object can be bound by this keyword when the function is invoked.

Advance Your MERN Stack Career in 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Advance Your MERN Stack Career in 6 Months!

Get Ahead of the Curve and Master Javascript and Full Stack Today

If you're an aspiring web and mobile developer, JavaScript training will broaden your skills and career horizons exponentially. You may be wondering how you can obtain the skills necessary to master this essential web programming skill.  

Look no further! Simplilearn offers a comprehensive Java Certification Training, which will help you become career-ready upon completion. 

Do you have any questions for us? Please leave them in the comments section, and we'll have our experts answer them for you.

About the Author

Taha SufiyanTaha Sufiyan

Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.