0

I'm reading Addy Osmani's 'Learning JavaScript Design Patterns' book. More precisely, a similar example is given in the book:

(function(){
  var Manager = {
    foo: function (param) {
      /*...*/
    },
    bar: function (param) {
      /*...*/
    }
  }
})();

The goal is to be able to do this:

Manager.execute("foo",param);

So the book shows this implementation:

Manager.execute = function ( name ) {
  return Manager[name] && Manager[name].apply( Manager, [].slice.call(arguments, 1) );
};

I've read this question on stackoverflow, but there are obvious changes from the example presented in the book. However I cannot understand how CarManager should be initialized and how it can work using that IIFE, since there is a closure with respect to all the functions of the CarManager itself. Why is this IIFE used in the book? Is this a mistake?

nostyn
  • 3
  • 3
  • Please read [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackoverflow.com/questions/125997/something-on-my-web-site-doesnt-work-can-i-just-paste-a-link-to-it). Questions that depend on external resources to be understood become useless when the external resource goes away or is fixed. Create a [MCVE] and put it in **the question itself** instead. Stackoverflow does support [inline live demos](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) – Quentin Sep 12 '21 at 10:12
  • So far that seems like a meaningless hack demonstrated with incomplete code snippets, and justified by pure nonsense (*For example, imagine if the core API behind the carManager changed. This would require all objects directly accessing these methods within our application to also be modified.*) – tevemadar Sep 12 '21 at 10:34
  • @Quentin It's ok like this? – nostyn Sep 12 '21 at 10:50
  • @tevemadar So I'm not forgetting anything, is this code or "design pattern" just wrong as it is described? – nostyn Sep 12 '21 at 10:50
  • 1
    One thing is that based on [wikipedia](https://en.wikipedia.org/wiki/Command_pattern), the command pattern would provide some kind of `execute()` call which has no arguments, but has encapsulated everything beforehand. [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) calls the targeted function in place, pre-populating something to be called later would be [`bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). That's the technical part. – tevemadar Sep 12 '21 at 14:42
  • And then comes the reasoning part which practically says that this way you can break your interface without breaking it. What is not true, just because the user can attempt to call a non-existing function (`Manager[name] &&` "check") and get an `undefined` instead of an exception, whatever the user wanted to happen won't happen. – tevemadar Sep 12 '21 at 14:45

0 Answers0