0

If I create a class, then I can use this within methods to set and retrive properties. However, this becomes undefined if I use a variable to refer to a method, as with variable b below:

class MyClass {
    methodA() {
        return this;
    }
}

var a = new MyClass();
var b = a.methodA;

console.log(a.methodA());
console.log(b());

Output:

MyClass {}
undefined

Why don't the log statements produce the same output?

William
  • 191
  • 8
  • var b = () => a.methodA(); – Angel Zlatanov Oct 01 '20 at 14:43
  • assigning method in this case without binding context would automatically set context (`this`) to global, which lead to your unexpected output. Changing to `var b = a.methodA.bind(a)` would help you – hgb123 Oct 01 '20 at 14:49
  • I think this question not dublicate – Anhdevit Oct 01 '20 at 14:49
  • When you call var b = a.methodA; b will be underline it only return when you call a.methodA() ``` class MyClass { methodA() { return this; } } var a = new MyClass(); var b = a.methodA(); console.log(a.methodA()); console.log(b()); ``` Output: ``` MyClass {} MyClass {} ``` – Anhdevit Oct 01 '20 at 14:49

0 Answers0