Static vs. function in JavaScript
Static vs. function in JavaScript
Can anyone explain why this is correct:
class Solution
static main()
console.log("Hello World!");
And why is this not correct?
class Solution
function main()
console.log("Hello World!");
I thought you always have to define a function with the function keyword.
class
function
2 Answers
2
Static class methods are not called on instances of the class, but on the class itself. MDN explains that quite well. As for the second part, that's just how the class
syntax works.
class
All right, thank you. Will accept when it's allowed in a few minutes.
– thesystem
Aug 27 at 8:39
class
is syntax sugar for this anyway:
class
function Solution()
Solution.main = function () ... ;
When they created the class
syntactic sugar to make it easier to write this kind of structure, they also decided to omit the requirement to type function
, since it's clear that main() ...
is a function definition in this context even without the function
keyword. There's nothing an additional "function
" would add to the meaning here, so why type it?
class
function
main() ...
function
function
Hmm, yeah that makes sense. Thanks for the explanation!
– thesystem
Aug 27 at 8:41
Just a follow up question, if you don't mind: I tried to omit
function
, so that it is the same structure as in the original question, but only ...main() {...
, but it still gives me an error - with other words, static
seems to be required. I am interested in why static
is required in this context?– thesystem
Aug 27 at 13:21
function
...main() {...
static
static
It gives you what error when you do what?
– deceze♦
Aug 27 at 13:23
I stated it in the OP. The second example I gave is not correct. I am interested in knowing why I have to use the keyword
static
within a class to define a function. If I do as in the second example from the OP, I get this error: Uncaught SyntaxError: Unexpected identifier
– thesystem
Aug 29 at 15:57
static
Uncaught SyntaxError: Unexpected identifier
Well, again, because the ECMAScript specification deems it unnecessary and in fact illegal to add a
function
keyword there. You either leave it out completely to define a regular instance method, or you add the optional keyword static
to define a class method. In neither case is function
a legal keyword there.– deceze♦
Aug 29 at 17:17
function
static
function
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That's just how the syntax works with
class
. See documentation Also, arrow functions do not need thefunction
keyword either.– CertainPerformance
Aug 27 at 8:35