They are not the same, and valid way to do it would be the first way.
Perhaps what you wanted to ask instead was the difference between these:
function() Obj {}
Obj.prototype.getName = function() {
console.log("my name");
};
var obj = new Obj;
vs this
function() Obj {
this.getName = function() {
console.log("my name");
};
}
var obj = new Obj;
well the answer is both are valid, first one adds function to prototype chain and second one adds to instance of the function.
Let's start with second one, simpler. After you run the code obj
will have function name getName Attached to itself. obj.getName()
will call the method on obj
.
Whereas in first one when you call obj.getName()
, the js compiler will look at obj
for method getName
and it will not be found there, so it will try look it up the chain. All objects in js have __proto__
property. Where another object is. When you create object trhough a function using new
keyword, resulted object's __proto__
is set to fucntion's prototype.
The advantage of delegating functions like this is that say you make 30 objects with this function then there wont be 30 getName methods as well. Instead, all object will still be referencing to prototype object which will have the getName
method. So there will be 30 references.