How to call another function within the same object?

Standard JS functions use dynamic binding, this is dependent on who’s calling the method on runtime, so if we call it using role.test(), it will bind this to role.

Arrow functions bind this to the current context. For example, if the code was writtern in the browser’s console, this is bound to the window object. This is called static lexical binding, which means binding this to the closure it was defined in.

If you won’t use arrow functions, this will point to the object itself when called by role:

const role = {
    test(variable){
        this.toLog(variable);
    },
    toLog(variable) {
        console.log(variable);
    }
};

role.test(5);

In this case, we don’t want to bind this to the outer context, so we’ll skip the static binding in favor of the dynamic one.

However, if we’ll use this method as a callback, dynamic binding will change this according to who’s running the method. To prevent that, we’ll have to use bind to create an explicit static binding to role.

const role = {
  test(variable) {
      this.toLog(variable);
    },
    toLog(variable) {
      console.log(variable);
    }
};

let test = role.test;

try {
  test(20); // will throw an error - this.toLog is not a function - because this points to window
} catch (e) {
  console.log(e);
}

test = role.test.bind(role);

test(25); // will work because it's staticly binded to role

Leave a Comment