Are you familiar with the OOP (Object Oriented Programming)?
Because right here what you see is an attempt to define an object in JavaScript, even though there is no class
keyword in JavaScript.
If you know a little bit about Java (which has just about nothing to do with JavaScript), then this should look familiar:
public class Animal { // creating a class
private String name; // declaring its attributes
public Animal(String name) { // declaring constructor
this.name = name; // assigning value to the attribute
}
}
The JavaScript code you gave does basically the same thing, e.g creating a class (some kind of enhanced type), that has both attributes (variables assigned to it) and methods (functions assigned to it).
So this code
function Animal(name) {
this.name = name;
}
creates the Animal
class.
The thing is that in JavaScript, there isn’t really any concept of class, but only of objects. So right here you create a variable and then you assign the result of the function that is following:
var Animal = (function() {
// some code here
})
(); // note the parenthesis here that means the function is called
Then, a constructor is defined, and the object containing this function is returned.
So at the end of the execution, the var Animal
contains a constructor, and thus any object can be initialized like this: ̀var myAnimal = new Animal('Panther');
.
Hope that helps.