Blaise
Blaise

Reputation: 13479

Obj.apply(Obj): is it safe and performant?

I came up with a simple design pattern that was inspired by several other design patterns. Its main purpose is to have private methods (instead of all global), methods visually nested and grouped within an object, and having "self" as an available variable to access the scope, which is really useful when using calling functions with a callback parameter.

It seems to work fine, but is it safe (performance - and scope-wise) to do Obj.apply(Obj);?

The code:

function Obj() {

    var self = this;

    var privateFunc = function() {
        console.log('private');
        self.otherPublic();
    };

    self.publicFunc = function() {
        console.log('pub1ic');
        privateFunc();
    };

    self.otherPublic = function() {
        console.log('pub2');
    };

} Obj.apply(Obj);

I call it like this:

Obj.publicFunc();

Upvotes: 1

Views: 107

Answers (1)

davin
davin

Reputation: 45525

Totally pointless brother. What you're doing by Obj.apply(Obj); is taking the function Obj, and adding to it those methods, in an unintuitive manner.

This:

var Obj = (function(){

  var priv = function(){ console.log('2'); },
      privVar = 6;

  return {
      pub1: function(){ console.log('1'); },
      pub2: function(){ priv(); }
  };

})();

Does the same thing, although better. I say better because (1) it's intuitive, and (2) Obj is now a simple javascript object (typeof Obj === 'object') whereas your Obj is a function with properties augmented (typeof Obj === 'function').

If you want a reference to self it's not hard (although it seems unnecessary), just create the object which will be returned at the top of the function, and augment the public methods, either at the end, or as you make them...

It's safe, but pointless.

Also, note that these methods won't scale well, because for each instance of Obj we create each function is recreated, which is memory-wise wasteful. This pattern above is fine because we created it with an anonymous function, so by definition there can only be one instance, although for types you need to instantiate multiple times the prototype should be used.

Don't be scared of it, it's there to be helpful.

UPDATE:

var Obj = (function(){

  var priv = function(){ pub2(); },
      privVar = 6,
      pub1 = function(){ priv(); },
      pub2 = function(){ console.log('1'); };

  return {
      pub1: pub1,
      pub2: pub2
  };

})();

Obj.pub1();

Notice that I call a public function, which calls a private function, which calls a public function - no special binding, no object reference.

UPDATE 2:

var Obj = (function(){

  var public = {},
      priv = function(){ public.pub2(); },
      privVar = 6;

  public.pub1 = function(){ priv(); },
  public.pub2 = function(){ console.log('1'); };

  return public;

})();

Obj.pub1();

Upvotes: 2

Related Questions