Reputation: 2901
Is there a difference between these two statements in Javascript?
function p() {
this.do = function(){alert('cool')};
}
and this one?:
function p(){};
p.prototype.do = function(){alert('cool')};
One more thing, why can't you do:
function p(){};
p.do = function(){alert('cool')};
Thank you so much!
Upvotes: 3
Views: 170
Reputation: 322452
Given your first two examples, assuming you call p()
as a constructor:
But the first example...
new p()
p()
constructor// p.prototype = {}
new p(); // { do:function(){alert('cool')}; } ------^
new p(); // { do:function(){alert('cool')}; } ------^
new p(); // { do:function(){alert('cool')}; } ------^
and the second example...
new p()
//p.prototype = {do:function(){alert('cool')};}
new p(); // {} ------^
new p(); // {} ------^
new p(); // {} ------^
The third example does not work because in JavaScript, a function is an object, so all you're doing it placing a new property on that object. It has no effect on the invocation of that function.
Upvotes: 3
Reputation: 105210
Functionally speaking, they are the same.
The first one defines a function for each object var o = new p()
so it is not optimal from a memory viewpoint.
You can do what you're showing in your 3rd example, but you're not going to accomplish what you think:
function p(){};
p.do = function(){alert('cool')};
p.do(); // this will work
var o = new p(); // This won't have the 'do' function because that's not how it works in javascript.
Upvotes: 0