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 設計模式
實字與建構式
   
43
物件實字語法
如果你不習慣物件實字,一開始它看起來會有點奇怪,但你越是用它,你將會越喜歡它。
基本上,物件實字語法是:

將物件用大括號包起來(
{ }

用逗號分隔物件內的每個屬性和函式。跟在最後一組名值對之後的逗號原本可被允
許,但在 IE 中會出錯,所以不要用它[40]

用分號分隔屬性名稱和屬性值

當你將物件賦值給一個變數,別忘了在最後的
}
之後加上分號
用建構式創造物件
JavaScript 沒有 class,而這反而允許了極高的彈性,因為你不需要知道事先知道任何
有關你物件的事情;你不需要一個 class 的「藍圖」。但 JavaScript 依然有建構式函式
constructor functions),它使用非常類似 Java 或其他語言中以 class 為基礎的物件建立
語法。
你可以用你自己的建構式函式建立物件,或使用這些內建的建構式,例如
Object()
Date()
String()
等等。
這裡有個例子展示使用兩種具有相同效果的方式,來創建兩個相同的物件:
你可以從此範例看到,物件實字明顯的優點是它的程式碼較短。而「實字是更好的物件建
立模式」的另一個理由是,它強調了物件僅僅是一個可變的雜湊表,而不是什麼需要從
「秘方」烘烤出爐的東西(意指來自一個 class)。
另一個使用實字而不是
Object
建構式的理由是,它不需要作用域的判斷。因為有可能你
會創造了相同名稱的區域建構式,所以解譯器需要從你呼叫
Object()
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