6 simple rules to fully understand "this" keyword in JavaScript 
Tags: beginners, javascript, webdev, codenewbie
Published: 2020-09-09 05:50:22

Hey! 👋
I'm Denis.

One of the most popular topics for a JavaScript interview is the **`this`** keyword. Even though this concept is fundamental, there are a lot of developers who don't really know the *rules* of `this` keyword. 

Actually there is nothing complicated. I want to share with you 6 simple rules that will help you to stand out among the other interviewees.

# **Rules**

### 1. **`new`** keyword
The first and the most important rule is that if the **`new`** keyword is used when we calling a function, inside this function `this` refers to a new object that is created and returned by the constructor function. This rule is also applicable when we use ES6 classes

#### Example
```js
function Person() {
  console.log(this)
  this.age = 23
  console.log(this)
}
const p = new Person()

/* Output */
// {}
// { age: 23 }
```

### 2. **`apply`** / **`call`** / **`bind`**
The rule that we all probably know is that when we can force a function call to use a particular object as `this` using one of these 3 methods: **`apply`** / **`call`** / **`bind`**

```js
function myFunction() {
  console.log(this)
}

const  thisObject = {
  someValue: 23
}

myFunction.call(thisObject)   // { someValue: 23 }
myFunction.apply(thisObject)  // { someValue: 23 }

const myBoundFunction = myFunction.bind(thisObject )
myBoundFunction()             // { someValue: 23 }
```

### 3. Function as a *method*
This one is quite popular for interviews. The rule is simple. When the function is called as a method (i.e., the function is called by a preceding dot), `this` is the object that the function is a property of (`this` is the object before that dot).
```js
const thisObject = {
  someValue: 23,
  itsMethod: function() {
    console.log(this)
  }
}

thisObject.itsMethod('John') // { someValue: 23, itsMethod: ƒ }
```

### 4. The simplest case
This is the simplest one, but a lot of people forget (or don't know) it. The rule says: if the function is called without any of the conditions above, `this` is the *`global`* object (`window`) for browser.

```js
function f() {
  console.log(this)
}

f() // Window (global object)
```

### 5. The order
If multiple rules can be applied simultaneously, the rule that is higher in the list will determine the `this` value.

### 6. Arrow functions
Arrow functions are the most favorite for interviews. Everyone knows that there's something special with `this` and arrow functions, but the minority really can tell the rule.

So, the rule is that arrow function **ignores** all the rules and takes the `this` value of its surrounding scope at the time it’s created. 

It's that simple! We can determine an arrow function's `this` value by finding the line where it was created and looking at what the value of `this` is there.


## Test yourself!
Let's test if you understand the rules 🙂.

```js
const obj = {
  value: 'abc',
  createFn: function() {
    return function() {
      console.log(this)
    }
  },
}
const fn = obj.createFn()
fn()
```

So, can you tell me what's going to be printed as `this` in this case? Can you clearly tell why? 

To test it you can simply run this code in chrome console.

But can you answer how to "fix" this code? 

If the answer is "Yes", congratulations! 🎉 You're one step closer to passing JavaScript interview!

## Conclusion
The rules of `this` are really simple, but knowing them you can definitely show understanding of the fundamentals to the interviewer.

Thanks a lot for reading my article. Feel free to subscribe to me on DEV and Twitter [@DenisVeleaev](https://twitter.com/DenisVeleaev).

Peace!