0

I am new to prototyping and constructor functions in JavaScript. I saw someone declare a constructor function in this way:

var Person = (function(){
    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 }

    return Person;
}());

Is this the correct way of doing it?

David Thomas
  • 249,100
  • 51
  • 377
  • 410

3 Answers3

1

Yes, it is the correct form, but not the only one. This is an equivalent to:

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 }

The code you presented wraps class declaration in one namespace, which is a good practice.

wachme
  • 2,327
  • 20
  • 18
1

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:

  1. A function
  2. Inside the function used as a constructor, use 'this' to modify the object being created
  3. 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.

David Atchley
  • 1,204
  • 8
  • 10
1

What others fail to mention is that within your IIFE all functions turn into closures, you can use that for shared private or protected members.

Pseudo-classical inheritance with privacy?

Since you're not using closure variables in the sample it's kind of useless to wrap it in an IIFE unless you like it for esthetic reasons.

More on prototype here:Prototypical inheritance - writing up

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
  • the post you linked to "Prototypical inheritance - writing up", seems like a real great place to read on the topic. Thanks for the link :) – aspnet learner May 05 '14 at 06:26