This question concerns non-strict mode.
I’m trying to understand JavaScript “this” binding. I understand that if we call a method directly object.m(...)
then this
will be bound to the object, but if the function is called separately, it isn’t. So I would expect (obj.m)(...)
to not bind this
but it does:
$ node
Welcome to Node.js v18.17.1.
Type ".help" for more information.
> var x = 34;
undefined
> let obj = {x:12, getx : function () { return this.x; }};
undefined
> obj.getx();
12
> (obj.getx)();
12
> let g = obj.getx;
undefined
> g();
34
> (((obj.getx)))();
12
> function test() { let g = obj.getx; return g(); }
undefined
> test();
34
> (true ? obj.getx : g)();
34
This leads me to believe that early on, the parser removes parens and reconnects the method call with the object. Are there other “optimizations” like this? Is this undefined behavior?