views:

78

answers:

5

I'm trying to understand the following code block and am a bit stumped.. specifically I'm confused as to what the YAHOO.example.XHR_JSON = part is about. It looks like we're creating an anonymous method that creates a named anonymous method?

YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.example.XHR_JSON = function() { (blah blah blah) };

If I try changing the YAHOO.exmaple.XHR_JSON to something like FooBar and I get told that foobar is not defined.

Any help is as always greatly appreciated..

A: 

There are two anonymous functions. The first sets YAHOO.example.XHR_JSON to the value of the second anonymous function. This isn't the same as defining a named function. It's just setting a variable to a value that is another function. It's a way of deferring execution. Maybe a second example would help:

var lightFuse = function() { bomb.actionToTakeIn30Seconds = function() { beep(); explode(); } }
Eric Mickelsen
A: 

This seems to be the line generating the confusion

YAHOO.example.XHR_JSON = function() { (blah blah blah) }; 

This is assigning a function object to a property XHR_JSON on the property example on YAHOO.

It could have been separated out as follows

var v1 = YAHOO.example
v1.XHR_JSON = function() { ( blah blah blah) };
JaredPar
+1  A: 

XHR_JSON is just a property of the YAHOO.example object. You can assign anything to this property, including a function.

If you tried the following:

YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.example.XHR_JSON = 'foobar';
});

.. then YAHOO.example.XHR_JSON will be set to 'foobar' eventually, but only after the load event has fired. That is probably why you got undefined when you checked for the value.

Daniel Vassallo
A: 

Sounds like you just needed to define FooBar first...? e.g.

var FooBar = function() { alert("Foo"); }
var OtherFunction = function() {
    this.myFunc = FooBar;
}
var instance = new OtherFunction();
instance.myFunc();
Kevin Nelson
A: 
var foo = funvtion(){... code ...};

is pretty much the same as

function foo() { ... code... };

The main idea of the code is that the XHR_JSON assignemnt is done after the "load" event of the page is triggered and all DOM elements are established.

Lucho