Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a global variable from a function's return value

Tags:

javascript

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;
like image 497
Mister Epic Avatar asked Oct 01 '22 07:10

Mister Epic


2 Answers

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.

like image 109
StriplingWarrior Avatar answered Oct 11 '22 14:10

StriplingWarrior


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.

like image 20
username tbd Avatar answered Oct 11 '22 14:10

username tbd