ITZone

Objects in JavaScript

Article purpose

Content

In real life, everything is an object. For example: cars, motorcycles, guitars, computers….

A car has properties like weight and color, and methods like start and stop.

All cars have the same attributes, but the attribute values differ between cars.

All vehicles have the same methods, but the methods are performed at different times.

Define an object

Objects are also variables. But objects can hold multiple values. Eg:

Click to see the results

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

Object Properties

Pairs name: value in JavaScript objects are called properties. Eg:

Then the properties would be:

Properties Value
firstName John
lastName Doe
age 21
eyeColor black

Access object properties

There are 2 ways to access object properties

Eg:

Click to see the results

Click to see the results

Object method

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions. Eg:

Properties Values
firstName Nguyễn
lastName Thiên
age 21
eyeColor black
fullName function() {return this.firstName + ” ” + this.lastName;}

Key word this.

Method access

We can also access a function via a method:

Eg:

Click to see the results

If you access a method without brackets (), it will return the function definition. Eg:

Click to see the results

Do not declare strings, numbers and Boolean as objects!

When a JavaScript variable is declared with the keyword new, this variable will be created as an object

They complicate our code and slow down execution.

Share the news now