Mister Epic
Mister Epic

Reputation: 16733

Creating a global variable from a function's return value

I'm looking at Addy Osmani's gist for a publication/subscription pattern here:

https://github.com/addyosmani/pubsubz/blob/master/pubsubz.js

He surfaces his object as a global like this:

;(function ( window, doc, undef ) {

var topics = {},
    subUid = -1,
    pubsubz ={};

....

getPubSubz = function(){
    return pubsubz;
};

window.pubsubz = getPubSubz();

What is the value of creating that getPubSubz function? Wouldn't it be more straightforward to simply write:

window.pubsubz = pubsubz;

Upvotes: 5

Views: 71

Answers (2)

username tbd
username tbd

Reputation: 9382

It absolutely would be.

There are only two potential reasons why a getter would be used in this case:

  1. There was previously some additional code inside the getter (logging, perhaps)
  2. Addy Osmani's just following good practice*, and including a getter—even adding the opportunity to add additonal code in the future.

Through the power of GitHub, we can actually eliminate option one, as the getter was added in its current state—so I think we can conclusively say that it's just a matter of good practice here.

*as jantimon alludes to in the comments below, this isn't particularly advantageous in most cases (including this one) and this code does not necessarily need to followed as an example.

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156554

Yes, in this case, because getPubSubz is only called in one place, immediately after declaring it, it could safely be inlined.

It's hard to say exactly what the author had in mind, but in a growing code base there may be some value to having a "getter" function which could be modified if the act of getting the pubsubz object required more advanced logic.

Upvotes: 2

Related Questions