What is this in Javascript?
Tags: javascript, programming, beginners, codenewbie
Published: 2019-12-06 10:32:31

---
canonical_url: https://www.blog.duomly.com/what-is-this-keyword-in-javascript/
---

This article was originally published at:
https://www.blog.duomly.com/what-is-this-keyword-in-javascript/

---


This keyword in Javascript is an important concept that makes a lot of confusion for beginners and more advanced developers as well. It’s very powerful, but it’s not so easy to use if you don’t know how it works.
In the article, I’m going to explain what is this keyword and what is its value in different cases, with code examples to make it even more apparent.

<h4>What is this?</h4>
Let’s first explain how Javascript code works to have a better understanding of what this keyword is. Every time we run Javascript in a browser, the engine executes a series of steps, and one of them is a creation of execution context. The execution context may be understood as an environment in which the Javascript code is running. Every execution context references the object, and this object usually refers to this keyword value. In other words, we may say that this keyword is a reference to the object, which called the function. The value of this keyword depends on where it is used.

<h4>this used alone</h4>
If this will be used alone, not in the context of any object or function, it will refer to the global scope. In the case of the browser, the global object name is a window. Let’s take a look on a simple code example:

```javascript
<script>
var fruit = "apple";
function getFruit() {
   var fruit = "banana";
   console.log("fruit", fruit); // „banana”
   console.log("this.fruit", this.fruit); // „apple”
}
returnFruit();
</script>
```

Let’s go through the example above to get more understanding of this keyword used alone. The getFruit() function was called in the global scope, and the first fruit variable is placed in the global scope as well. If you will console.log(this), the window object will have getFruit() method and fruit property.
At this point, when we are calling this.fruit, it will return “apple”, but the local variable fruit will return “banana”.
Our this here is window object so this.fruit refers to global fruit property.
It’s good to mention that in case of strict mode enabled, this in global scope is undefined.

<h4>this used with a method</h4>
In case of creating a new object from a constructor, then our this keyword refers to the new instance of the object.
Let’s take a look at the example:

```javascript
var firstName = "Peter";
var lastName = "Strong";
function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.returnName = function() {
    return this.firstName + ' ' + this.lastName;
  };
}
let newPerson = new Person("Kate", "Smith");
console.log(newPerson.returnName()); // "Kate Smith"
```

In the case of calling returnName() method, it will refer to the newPerson object, which was created using Person constructor, and our value will be „Kate Smith”, not „Peter Strong” because we are using newPerson object properties.

<h4>this used in a function</h4>
this keyword used inside a function can be a little tricky. It’s good to remember that function in Javascript is an object. It has its own properties, one of them is this and value its value depends on how it’s invoked. If the function is invoked by any object, then this value is the object. Otherwise, our function of this property is a global object — window. Let’s take a look at a code example.

```javascript
var catName = "Garfield";
var catColor = "orange";
function getCat() {
  return this.catName + ' is ' + this.catColor;
}
var cat = {
  catName = "Jerry",
  catColor = "gray",
  getCat: function() {
    return this.catName + ' is ' + this.catColor;
  }
}
```

console.log('Cat in gloabl scope', getCat()); // "Garfield is orage"
console.log('Cat in object scope', cat.getCat()); // "Jerry is gray"
If we analyze the code, we can see two functions, one of them is a global scope function, and one of them is a cat object method. While we are calling the global scope function getCat(), it uses global scope variables, because this keyword in the function refers to the global object. In the case of the getCat() method of cat object, this refers to cat object properties, and this is how we get 2 different results from such similar functions.

<h4>this used in the event</h4>
In case of events, after triggering any event, we call the event handler. These handlers are a function that is invoking some code. While we use this keyword in the event handler, this refers to the HTML element, which started the function. It’s good to remember that the DOM model is a tree of objects, so each HTML element on the page is stored as an object inside it. Let’s take a look at some example code:

```javascript
<button onclick="this.style.backgroundColor='blue'">Click here!</button>
```

Now we can see that using this, we can refer to the button HTML object and manipulate its styles, for example.

<h4>call(), apply() and bind()</h4>
There are three methods in Javascript which help us to set this value, it’s call(), apply() and bind().

Sometimes it happens that we want to borrow a method from the object and use it with the other context than the error will appear. Let’s take a look at the code:

```javascript
var boy = {
  greeting = 'Hello',
  sayHi: function() {
    return this.greeting;
  }
}
var spanishBoy = {
  greeting: 'Hola'
} 
boy.sayHi(); // "Hello";
```

What can we do if we would like to use sayHi() function but with a spanishBoy variable greeting? Here is where call(), apply() and bind() are handy. Let’s go through all of them and check what differences are.
<h4>call()</h4>

call() method allows us to assign this keyword new value. We can pass multiple arguments to call() method. The first argument is the value of new this, and next, we can pass function parameters. As a result, the function with new this and passed arguments is invoked. Let’s take a look a the code:

```javascript
var boy = {
  greeting = 'Hello',
  sayHi: function() {
    return this.greeting;
  }
}
var spanishBoy = {
  greeting: 'Hola'
} 
boy.sayHi(); // "Hello";
boy.sayHi.call(spanishBoy); // "Hola";
```

Here you can see the result of using the call() method. The sayHi() method was invoked immediately with the spanishBoy context, and we had a possibility to use the boy object method without creating a new method for spanishBoy object.

<h4>apply()</h4>
Let’s take a look at the next method, apply(). This method is very similar to call(), it also lets us change this value and invokes function immediately after it is used, but there is a small difference between them. While passing arguments to call() method, it looked like this: call(newThis, arg1, arg2, arg3). In case of an apply() function instead of passing each argument separately, we can pass them as an array, like this: ```apply(newThis, [arg1, arg2, arg3])```.

<h4>bind()</h4>
bind() method differs from call() and apply() a little. Instead of calling the function immediately, bind() creates and returns a new function with new this value assigned. Let’s take a look at the code example.

```javascript
var boy = {
  greeting = 'Hello',
  sayHi: function() {
    return this.greeting;
  }
}
var spanishBoy = {
  greeting: 'Hola'
} 
boy.sayHi(); // "Hello";
const sayHola = boy.sayHi.bind(spanishBoy);
sayHola(); // "Hola";
```

In this example, we can see that we were able to create a new function called sayHola(), and you can invoke it anytime.
Using bind() method may be very useful while dealing with asynchronous code or if you want to pass just a some of the parameters to your function.

<h4>Conclusion</h4>
In this article, I went through the definition and usage of this keyword in Javascript. I explained, what kind of this value you can expect in different scenarios, and described 3 important methods: call(), apply() and bind().

Take into consideration how important it is to understand this keyword to use it correctly and avoid lots of errors in your code, I hope you will find this article useful. Also, it’s good to remember that understanding the basics of Javascript will be very helpful in mastering more advanced concepts.

Thanks for reading,
Anna from Duomly

<a href="https://www.duomly.com">![Duomly - Programming Online Courses](https://thepracticaldev.s3.amazonaws.com/i/7gzh767o7e5dtvi1350p.png)</a>