First of all I'm sorry if this is a stupid question. I've written two code snippets bellow. The first code snippet found from here written by John Resig
and undoubtedly he's one of the bests and the second code snippet is modified by me from the original code only to understand the difference but I'm not sure actually what is the difference between both and what I can and can't do with both comparatively. Please someone help me to understand the difference. Thanks.
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, args.callee ? args : arguments );
}
else return new arguments.callee( arguments );
};
}
var User = makeClass();
User.prototype.init = function(first, last){
this.name = first + " " + last;
};
var user = User("John", "Resig");
console.log(user);
Modified version
function myClass(args)
{
if (this instanceof arguments.callee)
{
this.init = function(first, last){
this.name = first + " " + last;
};
this.init.apply( this, args.callee ? args : arguments );
}
else return new arguments.callee( arguments );
}
var obj = new myClass('Sheikh', 'Heera');
console.log(obj);
Why should I use the object's prototype to add a method (after making an instance) instead of writing it inside the constructor ?