Object methods in JavaScript

Keywords: Javascript Ubuntu Attribute Session

Original Link: https://www.html.cn/web/javascript/10448.html

Objects in JavaScript are collections of key/value pairs.Values can contain properties and methods, and can contain all other JavaScript data types, such as strings, numbers, and Boolean values.

All objects in JavaScript come from the parent object constructor.Objects have many useful built-in methods that we can use and access to simplify working with individual objects.Unlike array prototype methods such as sort() and reverse() used on an array instance, object methods are used directly for object constructors and object instances are used as parameters.This is the so-called static method.

Object.create()

Object.create() creates a new object and links the prototype of an existing object.

We can create an instance of a job object and extend it to more specific objects.

// 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()

Output:

The barista position is hourly and is accepting applications.

The barista object now has a property, position, but all other properties and methods in the job can be prototyped.Object.create() helps keep your code dry by minimizing duplication.

Object.keys()

Object.keys() creates an array containing object keys.

We can create an object and print an array of 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)

Output:

["boss", "secretary", "sales", "accountant"]

Object.keys can be used to iterate over the keys and values of an object.

// Iterate through the keys
Object.keys(employees).forEach(key => {
  let value = employees[key]

  console.log(`${key}: ${value}`)
})

Output:

boss: Michael
secretary: Pam
sales: Jim
accountant: Oscar

Object.keys are also useful for checking the length of objects.

// Get the length of the keys
const length = Object.keys(employees).length

console.log(length)

Output:

4

Using the length attribute, we can calculate four properties of employee.

Object.values()

Object.values() creates an array containing 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)

Output:

[1, "26-July-2018", "mobile", "Chrome"]

Object.keys() and Object.values() are simple and direct ways to return data from an object.

Object.entries()

Object.entries() creates a nested array of key/value pairs for an object.

// 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)

Output:

[
    ["name", "Ubuntu"]
    ["version", 18.04]
    ["license", "Open Source"]
]

Once we have a key/value pair array, we can easily cycle through and process the results using the forEach() method.

const entries = Object.entries(operatingSystem)
// Loop through the results
entries.forEach(entry => {
  let key = entry[0]
  let value = entry[1]
  console.log(`${key}: ${value}`)
})

Output:

name: Ubuntu
version: 18.04
license: Open Source

The Object.entries() method method will return only the properties of the object instance itself, not any properties that may be inherited through its prototype.

Object.assign()

Object.assign() is used to copy values from one object to another.

We can create two objects and merge them with'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)

Output:

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

You can also use the spread operator (...) to accomplish the same task.

// Merge the object with the spread operator
const character = { ...name, ...details }
console.log(character)

Output:

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

This extended grammar in object text is also known as shallow cloning.

Object.freeze()

Object.freeze() prevents you from modifying an object's properties and values and from adding or deleting attributes in the object.

// 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)

Output:

{username: "AzureDiamond", password: "hunter2"}

In this example, we try to override the password hunter2 with ******, but the password property remains unchanged.We also tried to add a new attribute, active, but we didn't.

isfrozen() can be used to determine if an object is frozen and return a Boolean value.

Object.seal()

Object.seal() prevents new attributes from being added to an object, but allows existing attributes to be modified.This method is similar to 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)

Output:

{username: "AzureDiamond", password: "*******"}

The new property active was not added to the sealed object, but the password property was successfully changed.

Object.getPrototypeOf()

Object.getPrototypeOf() is used to get the internal hiding of [[Prototype]] objects and is also accessed through the u proto_u property.

In this example, we can create an array that has access to the Array prototype.

const employees = ['Ron', 'April', 'Andy', 'Leslie']
Object.getPrototypeOf(employees)

Output:

[constructor: ?, concat: ?, find: ?, findIndex: ?, pop: ?, ...]

We can see in the prototype output that the employees array accesses pop, find, and other array prototype methods.We can verify this by testing the employees prototype.

Object.getPrototypeOf(employees) === Array.prototype;

Output:

true

This method can be used to get more information about an object or to ensure that it can access the prototype of another object.There is also a related Object.setPrototypeOf() method that adds a prototype to another object.It is recommended that you use Object.create() because it is faster and has higher performance.

conclusion

Objects have many useful ways to help us modify, protect, and iterate over them.In this tutorial, we review how to create and assign new objects, iterate over their keys and/or values, and freeze or seal objects.

Reference address for this article: https://www.html.cn/web/javascript/10448.html

Posted by kartul on Thu, 22 Aug 2019 18:53:29 -0700