DEV Community

Cover image for Understanding how `this` works in Javascript - The call-site
Kevin J. Estevez
Kevin J. Estevez

Posted on

Understanding how `this` works in Javascript - The call-site

If you have ever gotten your hands dirty with some javascript code, you'd maybe hit with this keyword's unexpected behavior, like it turd out to be undefined or you've probably declared a global variable, or maybe you just got another value but not what you were looking for.

If you're like me who came from a firm basis on Object Oriented Programming (aka OOP), and you're used to work with stuff like classes, class’s methods, instantiation, object's instance, constructors, etc. Then you'll notice in javascript this kind of concepts are slightly different and it tends to confuse.

Here specially I'm going to talk about the way this keyword works and the different kinds of how it could be bound to a function regardless either explicitly or implicitly. And what is the precedence of the binding methods?.

Let's get started ;)

4 types of binding this

  1. Default Binding
  2. Implicit Binding
  3. Explicit Binding
  4. new binding

And they have nothing to do with what we've learnt from classes by OOP.

In Javascript this is bound to an object and it depends on not where the function is declared but where the function is called.
So we should take a look at where the function is called to answer what does this reference to?

Let's get deep into some code:

function buzz() {
    // call-stack is: foo -> fizz -> buzz
    // then, our call-site is fizz

    console.log('buzz');
}

function fizz() {
    // call-stack is: foo -> fizz
    // then, our call-site is foo

    console.log('fizz');
    buzz(); // <-- call-site for buzz
}

function foo() {
    // call-stack is: foo
    // then, our call-site is in the global scope

    console.log('foo');
    fizz(); // <-- call-site for fizz
}

foo();  // <-- call-site for foo

You should be careful when you're analyzing your call-stack to determine what your actual call-site is.

The call-stack is the sequence of your functions called in order, then your call-site is the function called right before your actual function, for instance:

Initial First call Second call Third call
(empty stack) foo() fizz() buzz()
foo() fizz()
foo()

Being at the bottom of the stack, the first function called, and at the top of the stack, the last one.

Then if we were looking for the call-site for foo(), since there is nothing below, the call-site would be the global scope.

For fizz() the call-site would be foo.
For buzz() the call-site would be fizz.
An so on...

Now we understand better what the call-site is and where to find it, we may proceed to the next chapter: Default Binding

Thanks for reading ;)
I'll be writing the next posts of the series soon.

Top comments (0)