如何在 JavaScript 中使用對象方法
這篇文章最初是為 DigitalOcean 寫的。
簡介
JavaScript 中的對像是 key/value 的集合 對。這些值可以由 properties 組成 和方法 , 並且可能包含所有其他 JavaScript 數據類型,例如字符串、數字和布爾值。
JavaScript 中的所有對像都來自父 Object
構造函數。 Object
有許多有用的內置方法,我們可以使用和訪問以使處理單個對象更容易。不像 sort()
這樣的 Array 原型方法 和 reverse()
在數組實例上使用的對象方法直接在 Object
上使用 構造函數,並使用對象實例作為參數。這被稱為靜態方法。
為了充分利用本教程,您應該熟悉創建、修改和使用對象,您可以在了解 JavaScript 中的對像一文中查看這些內容。
Object.create()
Object.create() 用於創建新對象並鏈接現有對象的原型。在《了解 JavaScript 中的原型和繼承》中,我們了解了原型如何用於鏈接對象之間的屬性和函數。
我們可以創建一個 job
對象實例,並將其擴展到更具體的對象。
// Initialize an object with properties and methods
const job = {
position: 'cashier',
type: 'hourly',
isAvailable: true,
showDetails() {
const accepting = this.isAvailable
? 'is accepting applications'
: 'is not currently accepting applications'
console.log(
`The ${this.position} position is ${this.type} and ${accepting}.`
)
},
}
// Use Object.create to pass properties
const barista = Object.create(job)
barista.position = 'barista'
barista.showDetails()
The barista position is hourly and is accepting applications.
barista
對象現在有一個屬性 - position
- 但來自 job
的所有其他屬性和方法 可通過原型獲得。 Object.create()
通過減少重複來保持代碼 DRY 很有用。
Object.keys()
Object.keys() 創建一個包含對象鍵的數組。
我們可以創建一個對象並打印鍵數組。
// Initialize an object
const employees = {
boss: 'Michael',
secretary: 'Pam',
sales: 'Jim',
accountant: 'Oscar',
}
// Get the keys of the object
const keys = Object.keys(employees)
console.log(keys)
["boss", "secretary", "sales", "accountant"]
Object.keys
可用於遍歷對象的鍵和值。
// Iterate through the keys
Object.keys(employees).forEach((key) => {
let value = employees[key]
console.log(`${key}: ${value}`)
})
boss: Michael
secretary: Pam
sales: Jim
accountant: Oscar
Object.keys
對於檢查對象的長度也很有用。
// Get the length of the keys
const length = Object.keys(employees).length
console.log(length)
4
使用 length
屬性,我們能夠計算出 4
employees
的屬性 .
Object.values()
Object.values() 創建一個包含對象值的數組。
// Initialize an object
const session = {
id: 1,
time: `26-July-2018`,
device: 'mobile',
browser: 'Chrome',
}
// Get all values of the object
const values = Object.values(session)
console.log(values)
[1, "26-July-2018", "mobile", "Chrome"]
Object.keys()
和 Object.values()
是從對象返回數據的既簡單又直接的方法。
Object.entries()
Object.entries() 創建對象的鍵/值對的嵌套數組。
// Initialize an object
const operatingSystem = {
name: 'Ubuntu',
version: 18.04,
license: 'Open Source',
}
// Get the object key/value pairs
const entries = Object.entries(operatingSystem)
console.log(entries)
[
["name", "Ubuntu"]
["version", 18.04]
["license", "Open Source"]
]
一旦我們有了鍵/值對數組,我們就可以輕鬆地使用 forEach()
方法循環並處理結果。
const entries = Object.entries(operatingSystem)
// Loop through the results
entries.forEach((entry) => {
let key = entry[0]
let value = entry[1]
console.log(`${key}: ${value}`)
})
name: Ubuntu
version: 18.04
license: Open Source
Object.entries()
方法只會返回對象實例自己的屬性,不會返回任何可以通過其原型繼承的屬性。
Object.assign()
Object.assign() 用於將值從一個對象複製到另一個對象。
我們可以創建兩個對象,並將它們與 'Object.assign()` 合併。
// Initialize an object
const name = {
firstName: 'Philip',
lastName: 'Fry',
}
// Initialize another object
const details = {
job: 'Delivery Boy',
employer: 'Planet Express',
}
// Merge the objects
const character = Object.assign(name, details)
console.log(character)
{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
也可以使用擴展運算符(...
) 來完成同樣的任務。
// Merge the object with the spread operator
const character = { ...name, ...details }
console.log(character)
{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
對象字面量中的這種擴展語法也稱為淺克隆。
Object.freeze()
Object.freeze() 防止修改對象的屬性和值,並防止從對像中添加或刪除屬性。
// Initialize an object
const user = {
username: 'AzureDiamond',
password: 'hunter2',
}
// Freeze the object
const newUser = Object.freeze(user)
newUser.password = '*******'
newUser.active = true
console.log(newUser)
{username: "AzureDiamond", password: "hunter2"}
在示例中,我們嘗試覆蓋密碼 hunter2
與 *******
,但 password
財產保持不變。我們還嘗試添加一個新屬性 active
,但沒有添加。
Object.isFrozen()
可用於判斷一個對像是否被凍結,並返回一個布爾值。
Object.seal()
Object.seal() 防止將新屬性添加到對象,但允許修改現有屬性。該方法類似於Object.freeze()
.
// Initialize an object
const user = {
username: 'AzureDiamond',
password: 'hunter2',
}
// Seal the object
const newUser = Object.seal(user)
newUser.password = '*******'
newUser.active = true
console.log(newUser)
{username: "AzureDiamond", password: "*******"}
新的 active
屬性未添加到密封對象,但 password
屬性已成功更改。
Object.getPrototypeOf()
Object.getPrototypeOf() 用於獲取內部隱藏的[[Prototype]]
對象,也可以通過 __proto__
訪問 屬性。
在這個例子中,我們可以創建一個數組,它可以訪問 Array
原型。
const employees = ['Ron', 'April', 'Andy', 'Leslie']
Object.getPrototypeOf(employees)
[constructor: ƒ, concat: ƒ, find: ƒ, findIndex: ƒ, pop: ƒ, …]
我們可以在輸出中看到 employees
的原型 數組可以訪問 pop
, find
, 和其他 Array 原型方法。我們可以通過測試 employees
來確認這一點 針對 Array.prototype
的原型 .
Object.getPrototypeOf(employees) === Array.prototype
true
此方法可用於獲取有關對象的更多信息或確保它可以訪問另一個對象的原型。還有一個相關的Object.setPrototypeOf()
將一個原型添加到另一個對象的方法。推薦使用Object.create()
相反,因為它更快,性能更高。
結論
對像有許多有用的方法可以幫助我們修改、保護和迭代它們。在本教程中,我們回顧瞭如何創建和分配新對象、遍歷對象的鍵和/或值以及凍結或密封對象。閱讀Understanding Objects in JavaScript 來複習JavaScript 對象,Understanding Prototypes and Inheritance in JavaScript 來熟悉原型鏈。