在javascript中使用php風格的$globals
JavaScript有隱含的全域變數。當你不使用var來定義a = 1,而直接定義a=1時,這個變數a將成為一個全域變數。有的認為這是一個錯誤,應該避免全域變數,因為它們往往會在意想不到的地方出錯,尤其是在項目參與人員很多的情況下。
在PHP當中,預設的是局部變數。如果你需要一個全域變數,那麼你必須要將要聲明為全域變數的變數放到$globals這個數組中。
怎樣在javascripts中使用$globals呢?通過為全域公約在你的javascripts呢?在指令檔頂部聲明:
$GLOBALS = {};
那麼每一次當你需要一個全域變數,您可以這樣做:
$GLOBALS[ '' myglob '' ] = 1 ; / /非常像PHP的樣式
或者如果你喜歡,也可以這樣:
$globals.myglob = 1 ;
這樣做的優點:
*全域變數容易識別(甚至從飛機都可以看見)
*如果變數不定義成$GLOBAL,那麼它就是局部變數。如果變數沒有使用var,那麼它將產生一個錯誤
缺點:
*這種使用方法,不是官方規定的,不強制使用,只是一項約定俗成的方法。
Stoyan Stefanov''s Blog: PHP-style $GLOBALS in Javascript?
Javascript has implied globals. When you skip the var in var a = 1; and go a = 1;, then a becomes a global variable. Some consider this an error in the language. Global variables should be avoided because they tend to overwrite each other in unexpected places, especially if the project grows in LOC and number of developers.
In PHP on the other hand, variables are local. If you need a global variable, then you have to have to be explicit about it using the $GLOBALS superglobal array.
So how about this: adopt the $GLOBALS convention in your JavaScripts? At the top of the script you go:
$GLOBALS = {};
Then every time you need a global variable, you do:
$GLOBALS[''myglob''] = 1; // very PHP-like
or if you prefer:
$GLOBALS.myglob = 1;
Benefits of the approach:
• global variables easy to spot (even from an aeroplane)
• if it''s not $GLOBAL, it''s meant to be local. If it''s missing the var, it''s an error
Drawback:
• It''s a convention, so it can only help, but not enforce any coding practices