user2337247
user2337247

Reputation: 51

Is this bad use of javascript prototype?

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.

Upvotes: 1

Views: 125

Answers (2)

Dylan
Dylan

Reputation: 4773

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.

Upvotes: 0

plalx
plalx

Reputation: 43718

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 () {};
}

Upvotes: 1

Related Questions