Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading