Mastering JavaScript Objects: A Comprehensive Reference

Posted by Anonymous and classified in Computers

Written on in English with a size of 7.71 KB

Introduction to JavaScript Objects

In JavaScript, an object is a self-contained environment that stores data as a collection of properties and methods. A property is an association between a name (or key) and a value, while a method is a function associated with an object.

Think of an object as a real-world entity. For example, a Car is an object. It has properties like color, brand, and weight, and methods like start, drive, and brake.

// A simple conceptual look at an object
let car = {
    brand: "Tesla",       // Property (key: value)
    color: "Red",         // Property
    start: function() {   // Method
        console.log("Engine started!");
    }
};

Types of Objects in JavaScript

While almost everything in JavaScript is an object (or acts like one), they generally fall into three main categories:

1. Native / Built-in Objects

These are standard objects provided by JavaScript out of the box. They are part of the language specification.

  • Data Structures: Object, Array, Map, Set
  • Utility Objects: Math, Date, RegExp (Regular Expressions), JSON

2. Host Objects

These are supplied by the environment running JavaScript (like a web browser or Node.js).

  • Browser Environment (Web APIs): window, document (DOM), history, fetch
  • Node.js Environment: process, fs (File System), path

3. User-Defined Objects

These are custom objects created by you, the developer, to suit your specific application needs.

Creating Objects in JavaScript

There are several ways to create objects in JavaScript. Here are the most common methods:

1. Object Literal

The simplest and most readable way to create an object is using curly braces {}.

const user = {
    firstName: "Jane",
    lastName: "Doe",
    age: 28
};

2. Using the new Object() Syntax

You can use the built-in Object constructor (generally less preferred than the literal syntax).

const user = new Object();
user.firstName = "Jane";
user.lastName = "Doe";
user.age = 28;

3. Constructor Functions

Useful when you need a blueprint to create multiple objects of the same type. Conventionally, constructor functions start with a capital letter.

function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
}

// Creating instances
const user1 = new Person("Jane", "Doe", 28);
const user2 = new Person("John", "Smith", 34);

4. Object.create()

This method creates a new object, using an existing object as the prototype of the newly created object.

const protoUser = {
    greeting: function() {
        return `Hello, my name is ${this.name}`;
    }
};

const user = Object.create(protoUser);
user.name = "Jane"; // Inherits the greeting method

Object Methods

A method is simply a property containing a function definition. Methods allow objects to "do" things.

Defining Methods

You can define methods inside an object literal in two ways:

const calculator = {
    // Traditional way
    add: function(a, b) {
        return a + b;
    },
    // Modern ES6 shorthand (Recommended)
    subtract(a, b) {
        return a - b;
    }
};

console.log(calculator.add(5, 3));      // Output: 8
console.log(calculator.subtract(5, 3)); // Output: 2

Constructor Functions Explained

A Constructor Function is a regular function used as a blueprint to create multiple objects of the same type. To distinguish them from standard functions, they are conventionally named with a Capital Letter. To create an instance of an object using a constructor function, we use the new keyword.

function Player(name, level) {
    // 'this' refers to the new object being created
    this.name = name;
    this.level = level;
}

// Creating object instances
const player1 = new Player("Nova", 5);
const player2 = new Player("Viper", 12);

console.log(player1.name); // Output: Nova

What happens when the new keyword is used?

  1. A new empty object {} is created.
  2. The this keyword is bound to this new object.
  3. The code inside the constructor function executes, assigning properties to this.
  4. The newly created object is automatically returned (unless the function explicitly returns another object).

Prototypes in JavaScript

In JavaScript, every function and object has a built-in property called a Prototype. Prototypes are the mechanism by which JavaScript objects inherit features from one another.

  • Function.prototype: Every function has a prototype property. This is not the prototype of the function itself; rather, it is the blueprint that will be assigned as the prototype to any objects created by this function using the new keyword.
  • [[Prototype]] (or __proto__): Every object has an internal hidden link pointing to its constructor's prototype. In modern code, you inspect this using Object.getPrototypeOf(obj).

Instead of duplicating methods inside a constructor function for every single object instance, you should attach them to the function's prototype. This saves memory.

function Player(name, level) {
    this.name = name;
    this.level = level;
}

// Adding a method to the prototype
Player.prototype.levelUp = function() {
    this.level++;
    console.log(`${this.name} advanced to level ${this.level}!`);
};

const player1 = new Player("Nova", 5);
player1.levelUp(); // Output: Nova advanced to level 6!

Even though levelUp() is not defined directly inside player1, the object can access it because it exists on its prototype.

Inheritance Using the Prototype Chain

When you try to access a property or method of an object, JavaScript will first look for it directly on that object. If it cannot find it, it looks at the object's prototype. If it still can't find it, it looks at that prototype's prototype, and so on. This sequence is known as the Prototype Chain.

The chain ends when it reaches Object.prototype, whose prototype is null. If the property isn't found anywhere in the chain, JavaScript returns undefined.

Implementing Prototypal Inheritance

To make one constructor function inherit from another, we must manually link their prototype objects and fix the constructor reference.

// 1. Parent Constructor
function Character(name) {
    this.name = name;
}
Character.prototype.greet = function() {
    return `Hello, I am ${this.name}`;
};

// 2. Child Constructor
function Mage(name, spell) {
    // Call the parent constructor to inherit properties
    Character.call(this, name);
    this.spell = spell;
}

// 3. Link prototypes so Mage inherits Character's methods
Mage.prototype = Object.create(Character.prototype);

// 4. Reset the constructor pointer
Mage.prototype.constructor = Mage;

// 5. Add unique methods to the Child prototype
Mage.prototype.castSpell = function() {
    return `${this.name} casts ${this.spell}!`;
};

// --- Testing the Chain ---
const gandalf = new Mage("Gandalf", "Fireball");

console.log(gandalf.greet());     // Output: Hello, I am Gandalf
console.log(gandalf.castSpell());  // Output: Gandalf casts Fireball!

Related entries: