That works fine. That code declares the constructor function that way because it wants to keep the code related to a Person
in its own 'scope' or 'namespace', using an IIFE (Immediately Invoked Function Expression) that defines the actual constructor function and its prototype methods.
In general, to create a constructor function, you just need:
- A function
- Inside the function used as a constructor, use 'this' to modify the object being created
- call that function with the
new
operator
So, really, just doing:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setName = function(name) { this.name = name; }
Person.prototype.setAge = function(age) { this.age = age; }
var me = new Person('Tom', 38);
is all you need for your example. The IIFE scoping and returning the constructor function is just one way to create a type of 'module' for the Person type.