2011/6/13 Matthew Bramer <[email protected]>:
> I read this code and see there is one giant variable that starts with a
> self-executing function. This variable contains an object (pub) that has
> methods.

This is not a giant variable, just a large function, that returns a
smaller object. It also has a neat feature, that you can reference to
the variable `jQuery` inside the function as `$`, which results in
less typing inside the function without changing it in the global
scope.

> Why is the variable set to run a function automatically in a self-executing
> fashion? What would be the difference if the variable just equaled a
> function?
> var hackerNews = function( $, undefined ) {
> //stuff
> };

It wants to hide the 2 functions (`getNews` and `displayNews`) from
the global scope, but wants them to be available to the `pub` object
via this closure.

> Also towards the end of the function there is a return pub; statement. I can
> decipher this code as allowing hackerNews to gain access to the methods
> within pub, but why is the code structured like this? Being very new to
> JavaScript, I don't know what this is doing for me as a coder. The code
> looks great, but why is it structured like this and where can I find some
> documentation on why/when/how to use these techniques?

If you want to dig deeper into these patterns, look up a JavaScript
book about patterns, there are free ones like Essential JavaScript And
jQuery Design Patterns by Addy Osmani
<http://addyosmani.com/blog/essentialjsdesignpatterns> and there are
books like Pro JavaScript Design Patterns, JavaScript Patterns.

-- 
Poetro

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to