JS和YUI中的这些结构是什么?


What are these constructs in JS and YUI?

我从这里得到了以下代码,同时在一个单独的.js文件中搜索从YUI2 JavaScript函数访问PHP变量的某种方式。

查看JavaScript,第一个语句创建namespace ,第二个语句开始定义一个函数(命名为YAHOO.MyApp)。然后var currencyRates;var userInfo;创建两个变量。
  1. 那么下一个return {...}结构是什么?

  2. 里面是function(newRates) { currencyRates = newRates; }看起来像一个函数(特别是因为PHP可能会调用它)传递给它数组$currency rates ?但总的来说initCurrencyRates: function(newRates) { currencyRates = newRates; } ?

    什么是:那里(就像=是分配)?

  3. 那么最后的();呢?是什么something=function(){...}();结构?

谁能解释一下控制流程?首先执行什么,然后是什么,然后是什么?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>';
?>

您正在查看Javascript对象字面量。它们有点类似于PHP的散列文字。下面的Javascript代码

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

和下面的PHP代码有点类似:

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