1

I have a javascript module for creating Menu objects originally designed like this:

// original Menu module
function Menu ( ) {
    alert ( "Menu ( )");
}

Menu.prototype.init = function ( ) {
    alert ( "Menu.init ( )");
}

var menu = new Menu;

I now wish to wrap that inside my API like so

// new API containing Menu
( function ( $api, window, undefined ) {        

    $api.Menu = function ( ) {
        alert ( "$api.Menu ( )");
    };

    $api.Menu.prototype.init = function (  ) {
        alert ( "$api.Menu.init ( )");
    };

}( window.$api = window.$api || {}, window ));

var menu = new $api.Menu;

It appears to work but my question is whether this is correct? eg would this end up duplicating each prototype function for each $api.Menu instance?

I ask because I've always used prototype with the first method and I'm simply unsure what Javascript is doing under the hood for the second example.

user2337247
  • 51
  • 1
  • 4
  • In the second example, you're just executing similar code inside a function that is just called once - so either way works fine. The second way obviously puts the object in your namespace, but other than that, they both work fine. – jfriend00 Aug 19 '13 at 22:34
  • Excellent. Thanks for the very quick response. – user2337247 Aug 19 '13 at 22:41

2 Answers2

1

There isin't any difference between both in terms of efficiency, the only difference is that you are namespacing your constructor in the second example, which is a better practice than polluting the global namespace.

However the following would have been inefficient, since we would create a new init function everytime the constructor is getting called and we would not make use of the prototype chain at all to share functions between instances, resulting in a higher memory usage.

function Menu() {
    this.init = function () {};
}
plalx
  • 42,889
  • 6
  • 74
  • 90
0

They will all work, javascript is flexible like that.
I tend to prefer an object/class setup like:

function Menu(e){
   this.init(e);
}
Menu.prototype = {
   a:null,
   b:null,
   init:function(config){
      this.a = config.a;
   },
   doSomething:function(){
      this.b = 'World';
   },
   getSomething:function(){
       return this.a + ' ' + this.b;
   }
}

var menu = new Menu({a:'Hello'});
menu.doSomething();
alert(menu.getSomething());

You just have to remember to maintain scope as far as what "this" is.

Dylan
  • 4,703
  • 1
  • 20
  • 23
  • Please note that you may want to set the `prototype` constructor as well however. http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor – plalx Aug 20 '13 at 00:17