DEV Community

Cover image for 6 simple rules to fully understand "this" keyword in JavaScript
Denis Veleaev
Denis Veleaev

Posted on

32 10

6 simple rules to fully understand "this" keyword in JavaScript

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

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

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).

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.

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 πŸ™‚.

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.

Peace!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
skaytech profile image
skaytech β€’

Great Article Dennis! You kept it concise with practical examples. Well done :-)
I did write about the same topic a few weeks back, which was much more detailed. Do check it out -> dev.to/skaytech/what-is-this-in-ja...

Collapse
 
srikanth597 profile image
srikanth597 β€’

To fix it u can do any of this.
access it via closure instead of directly in the nested anonymous function i.e let that=this.
or manually apply bind(this) to nested function

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay