-3

The result of the following code is - undefined:

function f() {
    this.a = 1;
    return function() {
        console.log(this.a);
    };
}
(new f)();
tesicg
  • 3,971
  • 16
  • 62
  • 121
  • 1
    Possible duplicate of [What values can a constructor return to avoid returning this?](https://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this). When you return functions in a constructor, the result will be that function, not an object holding the `this` value, so `this.a` won’t be defined. – Sebastian Simon Jun 16 '18 at 05:29
  • Is `(new f)()` ever a valid syntax? –  Jun 16 '18 at 05:29
  • @Amy Yes, the parentheses with `new` are optional. – Sebastian Simon Jun 16 '18 at 05:29
  • Possible duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback . Also, this class seems to be semantically incorrect. There's no reason for it to be newed and use `this` – Estus Flask Jun 16 '18 at 05:34
  • It's a tricky interview question. – tesicg Jun 16 '18 at 05:41

1 Answers1

0

I think you're asking how to convert your anonymous function into an arrow function:

function f() {
    this.a = 1;
    return () => {
        console.log(this.a);
    };
}
(new f)();
Paul
  • 139,544
  • 27
  • 275
  • 264