Reputation: 7201
Creating a module I ended designing a pattern where I attach methods to a function, and I'm not sure if it is correct. It is a closure that returns a function that has some methods attached which in turn calls the function itself. I don't know if this is a bad practice or if it is considered to be ok. My objective is to provide ways to call the function with certain presents or in different ways, but I want to retain the ability to just call the function in its simpler form. Would this lead to memory leaks or anything like that?
I'm not making use of this at any point, so no danger of losing context.
Below you can find a code snippet with a simplified version.
function factory( general ){
var pusher = setTimeout(function(){ console.log('$',general) },1000);
var counter = 0;
function reporter ( specific ){
counter++;
console.log(counter, general , specific)
}
reporter.middleware = function ( something ){
clearTimeout(pusher);
return factory ( general + something )
}
return reporter
}
Thanks in advance.
Upvotes: 2
Views: 42
Reputation: 1075615
Would this lead to memory leaks or anything like that?
No more than anything else. :-)
Since functions are proper objects in JavaScript, you can add properties to them, and those properties can refer to other functions. At a technical level, it's not a problem at all. For instance, jQuery does it with its $
function, which not only is callable ($()
), but also has various other functions on it ($.ajax
, $.Deferred
, $.noConflict
, etc.).
Whether it's good style or design is a matter, largely, of opinion, so a bit off-topic for SO. It may well be fine. Or it may be that you'd be better off returning a non-function object with your various functions on it as properties.
Upvotes: 2