0

I am new to JavaScript and found that the 2 different methods below are able to instantiate object.

I looked the object created from both constructors and it appears to be same to me.

But I am not sure what is the difference between these 2 method? and in which scenario a method is better than another?

Can anyone please explain? Thank you.

Person1.js

function Person1(name){
    this.name = name;
    this.initialize();
}

Person1.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 1 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 1 class"+this);
    console.log(this);
    console.log("F1 Person 1 class caller"+caller);
    console.log(caller);
}

Person2.js

var Person2 = (function(){

function Person2(name){
    this.name = name;
    this.initialize();
}

Person2.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 2 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 2 class"+this);
    console.log(this);
    console.log("F1 Person 2 class caller"+caller);
    console.log(caller);
}

return Person2;
})();

Instantiate the object with this code:

var p1 = new Person1("P1");
var p2 = new Person2("P2");

console.log("Completed ");
console.log("P1 ");
console.log(p1);
console.log("P2 ");
console.log(p2);
user2763829
  • 793
  • 3
  • 10
  • 20

1 Answers1

1

Person2 is wrapped in what's called an immediately invoked funciton expression (or IIFE). You'll notice that at the end, it returns Person2, and that's why the assignment on the first line of the example works.

The reason you would consider using this method is that wrapping up code in an IIFE keeps you global scope clean (meaning, that in a browser for example, the window object doesn't get cluttered with a bunch of global properties).

As a beginner, I might go for the Person1 method, as it's visually simpler and easier to track what's going on. As you progress, however, keep the above in mind and think about what's best for the maintainability of your code base.

wbadart
  • 2,583
  • 1
  • 13
  • 27