Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
函式
   
63
名函式表達式,
name
屬性都有定義。對匿名的函式表示式,則依賴於實作方式;可能是
(在 IE 上),也可能是個空字串(在 FirefoxWebKit 上):
使用除錯工具時,例如 Firebug
name
屬性會很有用。當除錯工具需要在一個函式中顯示
錯誤,它可以檢查
name
屬性是否存在,並用它作為判斷指標。
name
屬性也被用來遞迴
呼叫自己。如果你對這兩種情況都沒興趣,那麼不具名的函式表示式會比較簡單也較不
囉嗦。[60]
反對採用函式宣告式,而認為使用函式表示式比較好的理由是,因為表示式突顯出函式就
是物件,就跟其他所有物件一樣,而不是什麼特殊的語言結構。
技術上是可以將一個具名函式表示式指派給有著另一個名稱的變數,例如:
var foo = function bar() {};
然而這種用法產生的行為在某些瀏覽器(IE 上未被正確的實作,所以不建議用這種模式。
函式的 Hoisting
從前面的討論中你可能會得出這樣的結論:函式宣告式和具名的函式表示式的行為非常接
近。但這不全然是對的,因為他們的不同處就在於 hoisting 行為。
Hoisting 此術語並未定義在 ECMAScript 中,卻是描述這種行為常見的好方法。
正如你所知道 的,所有的變 數,不論定義在 函式本體中的 哪裡,都會在幕 後被提升
hoisted)到函式的最前端。這行為也適用於函式,因為它們也只是賦值給變數的物件。
唯一讓人意想不到
譯著1
的是,函式宣告式,不只是
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190