Page 1 of 1

Javascript oddity (?)

Posted: Thu Jun 22, 2017 4:53 pm
by UK_Eliter
I've just discovered a really irritating feature of (only Oolite?) Javascript. To wit: if one has a function that has no arguments, and one calls it, but not by
this.$whatTheFuck()
but by
this.$whatTheFuck
i.e. without the parentheses, then the function does not run and . . one gets no error message. Argh!

Re: Javascript oddity (?)

Posted: Thu Jun 22, 2017 5:27 pm
by another_commander
The grammar of Javascript dictates that a function is called using the parentheses. Not using parentheses is simply not invoking the function. When you do a this.myFuntion you just get back a pointer to the function object. Since you are not using the returned value for anything, really what you have there is a statement with no effect.

If I go to the Debug Console and type for example:
system.sendAllShipsAway()
I get the function called and all ships hyperspace. If I do though
system.sendAllShipsAway then the console responds with:

Code: Select all

function sendAllShipsAway() {
    [native code]
}
which means "I recognize what you typed there as a function object". I could assign this object to a variable and do something with it, but if I just type it then that's an operation without any effect. Certainly it is not an error.

BTW, topic moved as it has little to do with optimization techniques.

Re: Javascript oddity (?)

Posted: Thu Jun 22, 2017 5:28 pm
by hoqllnq
I am not a javascript guru, but in any language I know, without the parentheses it is not a function call. It is just an expression that resolves to a value of the type 'function', that 'points to' / has the value of $whatTheFuck.
In a compiled language you'd get a warning for this along the lines of 'statement has no effect' or 'expression result not used'.

Re: Javascript oddity (?)

Posted: Thu Jun 22, 2017 7:10 pm
by Norby
another_commander wrote: Thu Jun 22, 2017 5:27 pm
system.sendAllShipsAway
An important usage is to check whether the function is exists at all or not. I often check this on new core features instead of raising the required Oolite version if I can make a workaround into the else block.

Moreover in the case of trunk sometimes it is not enough to check just the Oolite version: when somebody use an outdated trunk with the same version number but without a wanted new function. This is why I like to check the existence of the new function before I call it.

Re: Javascript oddity (?)

Posted: Fri Jun 23, 2017 12:36 am
by UK_Eliter
Norby wrote: Thu Jun 22, 2017 7:10 pm
Moreover in the case of trunk sometimes it is not enough to check just the Oolite version: when somebody use an outdated trunk with the same version number but without a wanted new function. This is why I like to check the existence of the new function before I call it.
Oh man, that's a whole new level of rubustness that, given limited time, I am not even going to try to attain. Respect!