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);