I am not clear on the actual difference between these two styles of “class” definitions in JavaScript.
Method a:
function myclass() {}
Method b:
myclass = function() {}
Is there any difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Those are functions, the first one is a function declaration, the second is a variable assignment with a function expression.
The main difference is that the function declarations are hoisted up in the current scope at parse time, they behave like if you declared them at the top of its enclosing scope.
The grammar of both is very similar, the only grammatical difference is that the name function expressions is optional, the parser knows which one you are using based on the “context” where you use it, e.g. your first example is a function declaration because the function itself is defined on a
Program(technically a place outside of any function, in the global scope), or inFunctionBody(inside a function).A function expression is created when it is evaluated itself in expression context, e.g.:
In the above example the second one is interpreted as a function expression because is surrounded by parentheses, and parentheses can only hold expressions…
I highly recommend you the following in-depth article about the topic: