I have been re-factoring someone else\'s JavaScript code.
BEFORE:
function SomeObj(flag) {
var _private = true;
this.flag = (fla
Question by question:
Basically, having the reset
method in the prototype
means that all instances of your constructor will share the exact same copy of the method. By creating a local method inside the constructor, you'll have one copy of the method per instance, which will consume more memory (this may become a problem if you have a lot of instances). Other than that, both versions are identical; changing function SomeObj
to var SomeObj = function
only differs on how SomeObj
is hoisted on its parent scope. You said you "gained some privacy with the variable declarations", but I didn't see any private variables there...
With the IIFE approach you mentioned, you'll lose the ability to check if instance instanceof SomeObj
.
Not sure if this answers your question, but there is also Object.create, where you can still set the prototype, but get rid of the new
keyword. You lose the ability to have constructors, though.