Search code examples
javascriptobjectmethodsargumentsthis

Pass an object's method to a function in Javascript. Is this the correct interpretation of the question?


I was in an interview, and there was this question:

When the method X of an object O is passed to a function Y as a parameter, what happens if X contains a reference to 'this' and gets executed inside Y? Please provide code examples.

Is this code a correct interpretation of the question?

let O = {
  name: 'John',
  age: 30,
  X() {
    console.log(this.name);
  },
};
let generic = O.X();

function Y(param) {
  return param;
}
console.log(Y(generic));

Could you please help me understand and reply to the question, even if just with an example?


Solution

  • The question asks if the function is passed, not if the function is invoked immediately, then passed. They were probably thinking of something like this:

    let O = {
      name: 'John',
      age: 30,
      X() {
        console.log(this.name);
      },
    };
    function callbackInvoker(fn) {
      fn();
    }
    callbackInvoker(O.X);

    As you can see, unless the passed method is bound first, or is an arrow function, its this binding to the O object will have been lost, which is probably what the question was intending to test you about.