DEV Community

Arun Kumar G
Arun Kumar G

Posted on

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

Top comments (0)