Javascript create objects and methods

How To Use Object Methods in JavaScript

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

All objects in JavaScript descend from the parent Object constructor. Object has many useful built-in methods we can use and access to make working with individual objects straightforward. Unlike Array prototype methods like sort() and reverse() that are used on the array instance, Object methods are used directly on the Object constructor, and use the object instance as a parameter. This is known as a static method.

This tutorial will go over important built-in object methods, with each section below dealing with a specific method and providing an example of use.

Prerequisites

In order to get the most out of this tutorial, you should be familiar with creating, modifying, and working with objects, which you can review in the “Understanding Objects in JavaScript” article.

For additional guidance on JavaScript in general, you can review our How To Code in JavaScript series.

Object.create()

The Object.create() method is used to create a new object and link it to the prototype of an existing object.

Читайте также:  Php header content type 1251

We can create a job object instance, and extend it to a more specific object.

// 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 one property — position — but all the other properties and methods from job are available through the prototype. Object.create() is useful for keeping code DRY by minimizing duplication.

Object.keys()

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

We can create an object and print the 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"]

As Object.keys converts your object’s keys into an array of keys, the forEach() array method can be used to iterate through the keys and values.

// 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 is also useful for checking the length of the converted array using the length property.

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

Using the length property, we were able to count the 4 properties of employees .

Object.values()

Object.values() creates an array containing the values of an object.

// 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() allow you to return the data from an object.

Object.entries()

Object.entries() creates a nested array of the key/value pairs of 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 the key/value pair arrays, we can use the forEach() method to loop through and work with the results.

// 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 will only return the object instance’s own properties, and 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); 

It is also possible to use the spread operator ( . ) to accomplish the same task. In the code below, we’ll modify how we declare character through merging the name and details objects.

// Initialize an object const name =  firstName: 'Philip', lastName: 'Fry' >; // Initialize another object const details =  job: 'Delivery Boy', employer: 'Planet Express' >; // Merge the object with the spread operator const character = . name, . details> console.log(character); 

This spread syntax in object literals is also known as shallow-cloning.

Object.freeze()

Object.freeze() prevents modification to properties and values of an object, and prevents properties from being added or removed from an 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); 

In the example above, we tried to override the password hunter2 with ******* , but the password property remained the same. We also tried to add a new property, active , but it was not added.

Object.isFrozen() is available to determine whether an object has been frozen or not, and returns a Boolean.

Object.seal()

Object.seal() prevents new properties from being added to an object, but allows the modification of existing properties. This method is similar to Object.freeze() . Refresh your console before implementing the code below to avoid an error.

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

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

Object.getPrototypeOf()

Object.getPrototypeOf() is used to get the internal hidden [[Prototype]] of an object, also accessible through the __proto__ property.

In this example, we can create an array, which 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 output that the prototype of the employees array has access to pop , find , and other Array prototype methods. We can confirm this by testing the employees prototype against Array.prototype .

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

This method can be useful to get more information about an object or ensure it has access to the prototype of another object.

There is also a related Object.setPrototypeOf() method that will add one prototype to another object.

Conclusion

Objects have many useful methods that help us modify, protect, and iterate through them. In this tutorial, we reviewed how to create and assign new objects, iterate through the keys and/or values of an object, and freeze or seal an object.

If you need to review JavaScript objects you can read “Understanding Objects in JavaScript.” If you would like to familiarize yourself with the prototype chain, you can take a look at “Understanding Prototypes and Inheritance in JavaScript.”

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Tutorial Series: How To Code in JavaScript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

Источник

JavaScript Objects

In JavaScript, objects are king. If you understand objects, you understand JavaScript.

In JavaScript, almost «everything» is an object.

  • Booleans can be objects (if defined with the new keyword)
  • Numbers can be objects (if defined with the new keyword)
  • Strings can be objects (if defined with the new keyword)
  • Dates are always objects
  • Maths are always objects
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are always objects

All JavaScript values, except primitives, are objects.

JavaScript Primitives

A primitive value is a value that has no properties or methods.

3.14 is a primitive value

A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:

Examples

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Immutable

Primitive values are immutable (they are hardcoded and cannot be changed).

if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

Value Type Comment
«Hello» string «Hello» is always «Hello»
3.14 number 3.14 is always 3.14
true boolean true is always true
false boolean false is always false
null null (object) null is always null
undefined undefined undefined is always undefined

Objects are Variables

JavaScript variables can contain single values:

Example

JavaScript variables can also contain many values.

Objects are variables too. But objects can contain many values.

Object values are written as name : value pairs (name and value separated by a colon).

Example

A JavaScript object is a collection of named values

It is a common practice to declare objects with the const keyword.

Example

Object Properties

The named values, in JavaScript objects, are called properties.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue

Objects written as name value pairs are similar to:

  • Associative arrays in PHP
  • Dictionaries in Python
  • Hash tables in C
  • Hash maps in Java
  • Hashes in Ruby and Perl

Object Methods

Methods are actions that can be performed on objects.

Object properties can be both primitive values, other objects, and functions.

An object method is an object property containing a function definition.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function()

JavaScript objects are containers for named values, called properties and methods.

You will learn more about methods in the next chapters.

Creating a JavaScript Object

With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

  • Create a single object, using an object literal.
  • Create a single object, with the keyword new .
  • Define an object constructor, and then create objects of the constructed type.
  • Create an object using Object.create() .

Using an Object Literal

This is the easiest way to create a JavaScript Object.

Using an object literal, you both define and create an object in one statement.

An object literal is a list of name:value pairs (like age:50) inside curly braces <>.

The following example creates a new JavaScript object with four properties:

Example

Spaces and line breaks are not important. An object definition can span multiple lines:

Example

This example creates an empty JavaScript object, and then adds 4 properties:

Example

const person = <>;
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;

Using the JavaScript Keyword new

The following example create a new JavaScript object using new Object() , and then adds 4 properties:

Example

const person = new Object();
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;

The examples above do exactly the same.

But there is no need to use new Object() .

For readability, simplicity and execution speed, use the object literal method.

JavaScript Objects are Mutable

Objects are mutable: They are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of person:

The object x is not a copy of person. It is person. Both x and person are the same object.

Any changes to x will also change person, because x and person are the same object.

Example

const person = <
firstName:»John»,
lastName:»Doe»,
age:50, eyeColor:»blue»
>

const x = person;
x.age = 10; // Will change both x.age and person.age

Источник

Оцените статью