DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on • Edited on

11 7

What is 'this' in JavaScript

What does 'this' return?

Here's an object which uses this keyword

const man = {
  name: "rick",
  adventure() {
    console.log(this);
  }
};

man.adventure(); 
Enter fullscreen mode Exit fullscreen mode

Executing above you will see the man object on the console.

Alt Text

But what if you do;

const adventure_reference = man.adventure;

adventure_reference();
Enter fullscreen mode Exit fullscreen mode

Output then would be;

Alt Text

Explanation

Value of 'this' is determined by how a function is called;

  • If we call a function as a method in an object this will always return a reference to that object.

  • If we call a function as a standalone object - or outside an object this will return the global object which is the window object in browsers.

In the next post we will use bind() to solve the problem 'of returning the window object'

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (3)

Collapse
 
johnkazer profile image
John Kazer

Kinda exactly the reason I don't use this. Context dependent behaviour is a nightmare I can do without. A functional style of JavaScript is able to avoid it.

Collapse
 
g1itcher profile image
G1itcher

I'm sure you already know this, but it's worth saying for any beginners that stumble upon this article.

It's easy to avoid issues with "this" by mandating arrow functions be used either to wrap the required function or just define the functions as arrow functions originally.

Or use bind()

With arrow functions and bind there's not much need to do the old

self = this

solution.

Collapse
 
naveenkolambage profile image
Naveen Dinushka

no worries! :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️