As a c#/.net dev, I love to toy around with JavaScript in my spare time -- creating my own libraries/frameworks and such. Admittedly, they're not much (really nothing more than a loose collections of functions), but the purpose is to learn; not for other people to use.
I usually extend a basic JavaScript object this way
obj = function () {
//basic object stuff
this.method = function () {
//other stuff
};
return this;
};
This allows me to create other objects and chain methods together, which is really slick:
obj('arg1').method();
Two Examples: jQuery Knock-off, List-Item Sorter
However, I have recently seen, in much more function code than my own, objects accomplish the same functionality this way:
function obj(){
//stuff
}
obj.prototype.method = function () {
//stuff
};
Example: Reddit Chrome Extension
Both ways seem to accomplish the same end, and I'm not partial to the look of either syntax. Is there a particular situation where one would be more useful than the other? What do these methods offer that makes them more desirable than the other?
Edit
Consider the following code:
var dice = function (sides) {
this.roll(){
return 4 //guaranteed to be random
}
};
var d1 = dice(6);
d1.roll() // 4;
var d2 = dice(20);
d2.roll() // 4
Are d1 and d2 different objects, as they appear to me? Or are they pointers/nicknames to one object (var dice)?