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?
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?
The latter is a closure which you are assigning to a variable. As soon as the variable is deleted (or is assigned a different value) you won't be able to call the function anymore. Besides that both are pretty much the same as functions are first class citizens in Javascript.
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 in FunctionBody (inside a function).
A function expression is created when it is evaluated itself in expression context, e.g.:
function foo () {} // function declaration
(function foo() {}); // function expression
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:
Firstly, you're defining functions, not classes.
Secondly, the second definition will put the myclass into the global namespace, whereas the first will not (it would be defined in function scope instead). However, so far as I'm aware, the following are roughly equivalent:
function myclass() {}
and
var myclass = function() {}
There are some small differences, which are explored over on developer.mozilla.org. Having said that, I've never noticed any of the differences.
In the second case, you are declaring the function as a variable. It is particularly useful for something like this in OOP:
var myObject = new Object();
myObject.add = function(a,b) {
return a + b;
};
myObject.add(1, 2);