I see objects in JavaScript organized most commonly in the below two fashions. Could someone please explain the difference and the benefits between the two? Are there cases where one is more appropriate to the other?
Really appreciate any clarification. Thanks a lot!
First:
var SomeObject;
SomeObject = (function() {
function SomeObject() {}
SomeObject.prototype.doSomething: function() {
},
SomeObject.prototype.doSomethingElse: function() {
}
})();
Second:
SomeObject = function() {
SomeObject.prototype.doSomething: function() {
},
SomeObject.prototype.doSomethingElse: function() {
}
}
Both of those examples are incorrect. I think you meant:
First:
(Note the return at the end of the anonymous function, the use of
=rather than:, and the semicolons to complete the function assignments.)Or possibly you meant:
(No anonymous enclosing function.)
Second:
(Note that the assignment to the prototype is outside the
SomeObjectfunction; here, we use:because we’re inside an object initializer. And again we have the;at the end to complete the assignment statement.)If I’m correct, there’s very little difference between them. Both of them create a
SomeObjectconstructor function and add anonymous functions to its prototype. The second version replaces theSomeObjectconstructor function’s prototype with a completely new object (which I do not recommend), where the first one just augments the prototype that theSomeObjectconstructor function already has.A more useful form is this:
There, the functions we assign to
doSomethinganddoSomethingElsehave names, which is useful when you’re walking through code in a debugger (they’re shown in call stacks, lists of breakpoints, etc.). The anonymous function wrapping everything is there so that thedoSomethinganddoSomethingElsenames don’t pollute the enclosing namespace. More: Anonymouses anonymousSome of us take it further:
…so that not only do we see
doSomething, butSomeObject$doSomethingin the lists. Sometimes that can get in the way, though, it’s a style choice. (Also note I used the anonymous function to enclose an alias forSomeObject.prototype, to make for less typing.)