DEV Community

Spyros Argalias
Spyros Argalias

Posted on • Originally published at sargalias.com

2 2

This binding in JavaScript - 2. Implicit binding

This post (This binding in JavaScript - 2. Implicit binding) was originally published on Sargalias.

In this series we talk about this binding in JavaScript.

This is a very important topic. It's also something that even experienced developers frequently get wrong and / or have to think about.

Basically in JavaScript there are 4 modes for this binding. Make that 5 if we include arrow functions.

In order of lowest priority to highest priority, here they are:

  1. Default binding
  2. Implicit binding
  3. Explicit binding
  4. New binding
  5. Arrow functions
  6. Gotchas and final notes

In this post we'll talk about implicit binding.


Implicit binding is what we get when we call a function with a "." before it, such as obj.foo().

How implicit binding works

Implicit binding has a higher precedence than default binding.

You use implicit binding by calling a function with a "." before it. For example obj.foo() results in implicit binding.

When using implicit binding, the value of this is the object just before the final "." before the function.

For example in obj.foo(), the value of this in foo is obj.

In objA.objB.foo(), the value of this in foo is objB.

In objA.objB.objC.foo(), the value of this in foo is objC.

Basically the value of this is the object at the very right of the function call before the actual function.

Example for implicit binding

Consider the following code.

'use strict';

const obj = {
  foo() {
    console.log(this);
  },
};

obj.foo();
Enter fullscreen mode Exit fullscreen mode

What does the code above output?

Answer: {foo: f} (in Chrome), which is basically obj.

Explanation:

We are calling a function preceded by a "." before it, so we're using implicit binding.

The value of this inside our function becomes the object right before the final "." of the function call. In this case that is obj. Therefore this becomes obj.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

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.

View demo

👋 Kindness is contagious

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

Okay