5 ms·
While I know this is a rubyist thread, I want to chime in as a Javascript developer. You can almost do the same thing there - joy! Probably not the best way to
by warfangle 16y ago
While I know this is a rubyist thread, I want to chime in as a Javascript developer. You can almost do the same thing there - joy! Probably not the best way to do it, but it's 3AM and I'm writing off the top of my head. And it's a little bit messy. And it gets rid of that pesky emergency case.
Within the object constructor:
// assuming the desk object was inherited and accessible. There are several ways to do this.
var thisContext = this; // unless you want to do some weird stuff with calling a function that returns a function that calls a function
["flights", "local_transports", "hotels"].forEach(function(fn) {
thisContext[fn] = function() {
check_lunch_break && desk[fn](arguments);
};
});
Granted, this doesn't get your methods on the prototype, and will incur a cost every time you create one of these objects. If you properly inherited from the desk class, it will overwrite them. And the emergency function will work just fine, if defined on desk.
- troels 16y agoNitpickery indeed, but that won't work as expected. `fn` can be reused within the loop, depending on the runtime, so all methods will end up calling the same `desk[fn]`.
- warfangle 16y agoYou're right in that it won't work as expected - unless the desk methods are static. In reality, you would probably want to call desk[fn].call(thisContext, arguments);
- deleted 16y ago[deleted]
- sharkbrainguy 16y agoI think you might have misread the code. Each `fn` is bound exactly once, `forEach` is not a loop.
- troels 16y agoTouché