Objects in JavaScript

Tram Ho

Article purpose

  • Syntax for declaring objects
  • Using Objects in JavaScript

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:

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:

PropertiesValue
firstNameJohn
lastNameDoe
age21
eyeColorblack

Access object properties

There are 2 ways to access object properties

  • Way 1: objectName.propertyName
  • Way 2: objectName["propertyName"]

Eg:

Object method

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions. Eg:

PropertiesValues
firstNameNguyễn
lastNameThiên
age21
eyeColorblack
fullNamefunction() {return this.firstName + ” ” + this.lastName;}

Key word this.

  • In the function definition, this refers to the object that owns the function.
  • In the above example object person possess function fullName.
  • In other words, this.firstName means attribute firstName of this object.

Method access

We can also access a function via a method:

Eg:

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

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