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

How to change `this` in a lambda function returned by a getter

I have defined a class containing a getter returning a lambda function.
I’d like to change the "this" used in the function returned, but I did not find any way to do that. I made many tries with function.call but no matter what, I did not get the expected result. So I need help!

Here is some minimal code reproducing the problem:

class A {
    get fn() { return () => [this.name, this]; }
}
let a = new A();
a.name = "a";
let b = { name: "b" };
window.console.log(a.fn.call(b)); // How to get "b" ?

The result is :

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

[
  "a",
  {
    "name": "a"
  }
]

How to apply the returned lambda function to b ? and receive the expected result:

[
  "b",
  {
    "name": "b"
  }
]

>Solution :

You need to take a standard function instead of an arrow function.

class A {
    get fn() { return function () { return [this.name, this]; } }
}
let a = new A();
a.name = "a";
let b = { name: "b" };

console.log(a.fn.call(b)); // How to get "b" ?
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