DEV Community

Arun Kumar G
Arun Kumar G

Posted on

1

4 + 1 rules to understand this

Undestanding this

function foo(){
console.log(this.name);
}

There are four rules to identify what this refers to in a given context

  1. Default binding:

    • points to the global or window object foo();
  2. implicit binding

    • points to the object using which the method is innvoked;

    The object that is standing before the dot
    is what this keyword will be bound to.

    obj.foo();

  3. Explicit binding

    • possible to set explicit value by one of these methods obj.foo.apply(person,[]); obj.foo.call(person, ,,,,); foo.call(person,...);
  4. Constructor / new Binding

    • value is set the newly created/instantiated Object new Constructor();

And there is a priority, whic is 4 3 2 1

The above 4 rules apply inside a normal function, but not in arrow functions

Special case

Arrow functions

  • In case of an arrow function, 2,3,4 will not work.
  • Inside arrow function the value points to value of this which is in enclosing block where the method is invoked and not where its defined.``

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

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