1

I'm messing with AST and what I need (in a nutshell) is this:

(new Test().containsProperty ? new Test().anotherMethod : new Test().method)()

But it gives me Uncaught TypeError: Cannot read property '...' of undefined, because for some reason it treats this wanted in the method as undefined. Why?

class Test {
    constructor() {
        this.property = 'Test';
    }
    
    method() {
        alert(this.property);
    }
}

try {
//  Doesn't works
    (new Test().containsProperty ? new Test().anotherMethod : new Test().method)();
    
//  Either
//  (undefined || new Test().method)();
    
//  But this does
//  (new Test().method)();
} catch(error) {
    alert(error);
}
DIES
  • 183
  • 2
  • 10
  • It's equivalent to `let f = (new Test()...); f()`. And the fact that you call it as `f()` and not `someObj.f()` means it loses its context. You'll need to call the function with [`call`](http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and explicitly pass the context. – deceze Apr 12 '21 at 15:06
  • @deceze Very well. So I need to create forth instance to make it work in one line? – DIES Apr 12 '21 at 15:09
  • Yes. `const o = new Test; (o.a ? o.b : o.c).call(o)` – deceze Apr 12 '21 at 15:10

0 Answers0