JavaScript 內建物件是日常開發的基礎,以下依常見物件整理重要屬性與方法。
Date 用於處理日期與時間,常見方法有 getDay、getFullYear、getMonth、getDate、getHours、getMinutes、getSeconds、getTime、setFullYear、setMonth、setDate、toLocaleString、toUTCString。
Math 提供數學運算,常見屬性有 PI、E、LN2、LN10、SQRT2,方法包括 abs、ceil、floor、round、max、min、pow、sqrt、random、sin、cos、tan。
Number 代表數值,常見屬性有 MAX_VALUE、MIN_VALUE、NaN、NEGATIVE_INFINITY、POSITIVE_INFINITY,方法包括 toString 與 valueOf。
Boolean 代表布林值,可透過 toString 轉成字串,也可透過 valueOf 取得原始值。
String 提供 charAt、charCodeAt、concat、indexOf、lastIndexOf、match、replace、search、slice、split、substr、substring、toLowerCase、toUpperCase 等方法。
Array 的常用方法有 push、pop、shift、unshift、slice、splice、join、concat、sort、reverse、toString、valueOf。
RegExp 用於正則表達式,常見屬性有 source、global、ignoreCase、lastIndex,方法包括 test、exec、compile。
Function 有 arguments、caller、prototype 等屬性。Object 是所有物件的基礎,可透過 prototype 擴充屬性與方法。
全域屬性包括 Infinity、NaN、undefined。全域方法包括 parseInt、parseFloat、isNaN、isFinite、encodeURI、decodeURI、encodeURIComponent、decodeURIComponent、escape、unescape。
常見事件有 onload、onunload、onchange、onsubmit、onreset、onselect、onblur、onfocus、onkeydown、onkeypress、onkeyup、onclick、ondblclick、onmousedown、onmousemove、onmouseout、onmouseover、onmouseup、onerror。
自訂物件可以用物件字面值建立,也可以用建構函式建立。使用 new 時,函式會成為建構函式,並透過 this 指向新建立的物件。