在javascript中使用php風格的$globals – 馬永占 譯

來源:互聯網
上載者:User

著作權聲明:原創作品,允許轉載,轉載時請務必以超連結形式標明文章原始出版、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/mayongzhan - 馬永占,myz,mayongzhan

在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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.