Given your first two examples, assuming you call p()
as a constructor:
- on the surface, they will behave identically
But the first example...
- will create a new, identical function for each object created from
new p()
- [that function] will have access to the local variables and parameters inside the
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...
- will share the function placed on the prototype between all the objects created from
new p()
- [that function] will not have access to private variables/parameters in the constructor
//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.