JavaScript Classes


#1


Is there any difference? Are both of them correct way to create a class?


function Animal(name, numLegs)
{
    this.name = name;
    this.numLegs = numLegs;
};


or


var Animal = function(name, numLegs)
{
    this.name = name;
    this.numLegs = numLegs;
};


#2

The first one is a function statement, the second is an assignment statement that assigns the result of a function expression to a variable.
The function statement is hoisted, that function is created before execution reaches that line(s).
Semicolon isn't part of the function statement, so in your code you have an empty statement after the function statement.
Neither is a class, they are constructor functions. JS has a class keyword, but that is syntax-sugar for constructors, methods and inheritance. JS doesn't have classes in the sense that java or python has.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.