5

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;
1
  • He also uses undef although its not needed.. Commented Jul 17, 2014 at 18:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you give a concrete exmaple of how it will be useful? In other languages getters and setters are used for encapsulation but in this case I don't see the advantage.
@Hazaart: If the code grows to access the pubsubz object from many different places, and then one day you realize that you want to use a different pubSubz instance depending on the state of a toggle variable, it would be nice to only need to change the implementation of the getPubSubz method, rather than everything that's accessing it. Of course, in that case, it would be unwise to expose the object as a global variable. As I said, it's hard to know what the author had in mind there.
2

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.

1 Comment

@jantimon fine, it's not particularly advantageous for JS, you got me. Maybe just old habits from languages where it is good practice :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.