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 設計模式
設計模式
   
153
這裡是這行為的一些範例和測試。請注意在呼叫
Object
的時候加不加
new
都可以:
其實
Object()
也是一個 factory 這件事,並沒有什麼實際的用處,只是值得提一下這個例
子,來說明 factory 模式就在我們身邊。[148]
迭代器模式(Iterator
iterator 模式中,你有個包含了某種資料集的物件。這些資料也許儲存在一個複雜的結
構內,而你想要提供簡單的操作,來存取該結構的元素。客戶並不需要知道你是如何組織
資料的;他們只需要操作這些個別元素就可以了。
iterator 模式中,你的物件必須提供一個
next()
方法。在序列(sequence)中呼叫
next()
,必須回傳下一個元素,你可以自行決定所謂「下一個」在你特定的資料結構中的
意義。
假設你的物件稱作
agg
,你可以藉由一個迴圈呼叫
next()
以存取每一個資料元素:
iterator 模式,集合物件通常也會提供一個方便的
hasNext()
方法,於是物件的客戶可
以藉此判斷是否已經到達資料末端。接下來,介紹另一種依序存取每個元素的方法,這次
我們使用了
hasNext()
現在我們有使用案例了,讓我們來看看如何實作這個集合物件。
對元素做些操作 ...
對下一個元素做些操作...
154
   
第七章
在實作 iterator 模式的時候,我們將儲存的資料設為 private 並以一個 private 的索引指向下
一個可用的元素,這麼做頗為通情達理。為了
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