What are these constructs in JS and YUI?

49 Views Asked by At

I got the following code from here, while searching for some way to access PHP variables from a YUI2 JavaScript function in a separate .js file.

Looking at the JavaScript, the first statement creates the namespace, the second statement starts the definition of a function (named as YAHOO.MyApp). Then var currencyRates; and var userInfo; create two variables.

  1. Then what is the next return {...} construct?

  2. Then inside that, function(newRates) { currencyRates = newRates; } looks like a function (especially because PHP probably calls it and passes to it the array $currency rates? But overall what is initCurrencyRates: function(newRates) { currencyRates = newRates; }?

    What is : there (just like = is for assignment)?

  3. Then what about the (); in the end? What is the something=function(){...}(); construct?

Can somebody explain the control flow? What is executed first and then what and then what?

JavaScript:

YAHOO.namespace('MyApp');

    YAHOO.MyApp = function() {

    var currencyRates;
    var userInfo;

    /*
    here a lot of code with event listeners and dom manipulations which uses currencyRates and userInfo variables
    */

    return {
        initCurrencyRates: function(newRates) { currencyRates = newRates; },
        initUserInfo: function(newUserInfo) { userInfo = newUserInfo; },
    }

}();

PHP:

<?php
$currencyRates = array('EUR' : 1.3245, 'GBP': 1.4322, 'RUB': 0.02334); //actually it comes from database
print '<script>YAHOO.MyApp.initCurrencyRates(' . json_encode($currencyRates) . ')</script>';

$userInfo = array('Name' => 'Jhon', 'ID' => 10); //actually it comes from database
print '<script>YAHOO.MyApp.initUserInfo(' . json_encode($userInfo) . ')</script>';

?>
1

There are 1 best solutions below

5
hugomg On

You are looking at Javascript object literals. They are a bit similar to PHP's hash literals. This Javascript code

var foo = {
    x: "hello",
    y: "world"
}

Is a bit similar to this PHP code:

$foo = array(
    "x" => "Hello",
    "y" => "World"
)