JS closures - Passing a function to a child, how should the shared object be accessed

Posted by slicedtoad on Programmers See other posts from Programmers or by slicedtoad
Published on 2014-08-18T19:10:59Z Indexed on 2014/08/18 22:31 UTC
Read the original article Hit count: 288

I have a design and am wondering what the appropriate way to access variables is. I'll demonstrate with this example since I can't seem to describe it better than the title.

  • Term is an object representing a bunch of time data (a repeating duration of time defined by a bunch of attributes)
  • Term has some print functionality but does not implement the print functions itself, rather they are passed in as anonymous functions by the parent. This would be similar to how shaders can be passed to a renderer rather than defined by the renderer.
  • A container (let's call it Box) has a Schedule object that can understand and use Term objects.
  • Box creates Term objects and passes them to Schedule as required. Box also defines the print functions stored in Term.
  • A print function usually takes an argument and uses it to return a string based on that argument and Term's internal data. Sometime the print function could also use data stored in Schedule, though. I'm calling this data shared.

So, the question is, what is the best way to access this shared data. I have a lot of options since JS has closures and I'm not familiar enough to know if I should be using them or avoiding them in this case.

Options:

  1. Create a local "reference" (term used lightly) to the shared data (data is not a primitive) when defining the print function by accessing the shared data through Schedule from Box. Example:

    var schedule = function(){
        var sched = Schedule();
        var t1 = Term( function(x){   // Term.print()
                           return  (x + sched.data).format();
                     });
    };
    
  2. Bind it to Term explicitly. (Pass it in Term's constructor or something). Or bind it in Sched after Box passes it. And then access it as an attribute of Term.

  3. Pass it in at the same time x is passed to the print function, (from sched). This is the most familiar way for my but it doesn't feel right given JS's closure ability.
  4. Do something weird like bind some context and arguments to print.

I'm hoping the correct answer isn't purely subjective. If it is, then I guess the answer is just "do whatever works". But I feel like there are some significant differences between the approaches that could have a large impact when stretched beyond my small example.

© Programmers or respective owner

Related posts about design

Related posts about object-oriented