Home > Software engineering >  How to change `this` in a lambda function returned by a getter
How to change `this` in a lambda function returned by a getter

Time:02-13

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 :

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

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

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

CodePudding user response:

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" ?

  • Related