patternjavascriptMinor
Possibly mixing prototype and module pattern
Viewed 0 times
possiblymoduleprototypemixingandpattern
Problem
I have either created something beautiful or something monstrous, and I'm not really sure which, and I don't know where else to turn but here. What I've done:
To my surprise, this works, and takes care of a pretty significant problem of creating reusable private functions for various public functions. Of course, I have to do some scoping for the
My question is: is this a code smell? and as a corollary, is there a better way to do this?
var MyObject = function(opts) {
//init code, set vals, runs when 'new MyObject()' is called
}
MyObject.prototype = (function() {
//private helper functions
//scoping is a pain, but doable
function myPrivateFunction() {}
return {
publicFunc1: function() { /* uses myPrivateFunction() */ }
, publicFunc2: function() { /* uses myPrivateFunction() */ }
};
})();
MyObject.prototype.publicFunc3 = function() {}
MyObject.prototype.publicFunc4 = function() {}
MyObject.prototype.publicFuncEtc = function() {}To my surprise, this works, and takes care of a pretty significant problem of creating reusable private functions for various public functions. Of course, I have to do some scoping for the
this object, but I feel it's a small price to pay for being able to use private reusable functions. I left the other functions on the outside to avoid having to deal with scoping.My question is: is this a code smell? and as a corollary, is there a better way to do this?
Solution
The commenters pretty much said it all:
-
I would declare
Other than that, this code does not look monstrous to me, if it works for you, then why not.
publicFunc3can't seemyPrivateFunction
-
I would declare
function() { / uses myPrivateFunction() / } as a private function and then just return a pointer to it:MyObject.prototype = (function() {
//private helper functions
//scoping is a pain, but doable
function myPrivateFunction() {}
function myPrivateFunction2() {/* uses myPrivateFunction() */ }
function myPrivateFunction3() {/* uses myPrivateFunction() */ }
return {
publicFunc1: myPrivateFunction2
, publicFunc2: myPrivateFunction3
};
})();- I know there is a "comma first" movement out there, but it looks silly to me
Other than that, this code does not look monstrous to me, if it works for you, then why not.
Code Snippets
MyObject.prototype = (function() {
//private helper functions
//scoping is a pain, but doable
function myPrivateFunction() {}
function myPrivateFunction2() {/* uses myPrivateFunction() */ }
function myPrivateFunction3() {/* uses myPrivateFunction() */ }
return {
publicFunc1: myPrivateFunction2
, publicFunc2: myPrivateFunction3
};
})();Context
StackExchange Code Review Q#25454, answer score: 3
Revisions (0)
No revisions yet.