2.5.1 Creating Custom Objects
- Introduction: Custom objects in JavaScript represent complex data structures with properties and methods.
Using Object Literals
- Object literals allow for straightforward object creation.
- Simple Example:
let car = {
make: "Toyota",
model: "Camry",
year: 2020,
start: function() {
console.log("Car started");
}
};
More Complex Example:
let book = {
title: "1984",
author: "George Orwell",
pages: 328,
read: function() {
console.log(`Reading ${this.title} by ${this.author}`);
}
};
Using Constructor Functions
- Constructor functions create multiple instances of an object type.
- Simple Example:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
More Complex Example:
function Rectangle(width, height) {
this.width = width;
this.height = height;
this.area = function() {
return this.width * this.height;
};
}
Using ES6 Classes
- ES6 classes provide a structured way to create objects and handle inheritance.
- Simple Example:
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
More Complex Example:
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
getDetails() {
return `${this.year} ${this.make} ${this.model}`;
}
}
Summary
- Custom objects allow modeling of complex data structures.
- Use object literals for simple objects, constructor functions for multiple instances, and ES6 classes for structured approaches.
- Practice creating custom objects to enhance JavaScript skills.
2.5.2 Defining Properties and Methods
Defining Properties of Custom Objects
Properties in custom objects are variables that hold values, defining the characteristics or attributes of the object.
Example of Defining Properties:
Simple Example:
let person = {
name: "Alice",
age: 30
};
console.log(person.name); // Output: Alice
console.log(person.age); // Output: 30
Complex Example:
let car = {
make: "Toyota",
model: "Camry",
year: 2020,
color: "blue"
};
console.log(`Car: ${car.year} ${car.make} ${car.model}, Color: ${car.color}`);
// Output: Car: 2020 Toyota Camry, Color: blue
Defining Methods of Custom Objects
Methods in custom objects are functions that perform actions or calculations related to the object.
Example of Defining Methods:
Simple Example:
let person = {
name: "Alice",
age: 30,
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.sayHello(); // Output: Hello, my name is Alice
Complex Example:
let bankAccount = {
accountHolder: "Bob",
balance: 1000,
deposit: function(amount) {
this.balance += amount;
console.log(`Deposited: $${amount}. New balance: $${this.balance}`);
},
withdraw: function(amount) {
if (amount > this.balance) {
console.log("Insufficient funds.");
} else {
this.balance -= amount;
console.log(`Withdrew: $${amount}. New balance: $${this.balance}`);
}
}
};
bankAccount.deposit(500); // Output: Deposited: $500. New balance: $1500
bankAccount.withdraw(200); // Output: Withdrew: $200. New balance: $1300
bankAccount.withdraw(1500); // Output: Insufficient funds.
Summary
Defining properties and methods in custom objects is essential for creating structured and functional JavaScript applications. Properties represent the attributes of the object, while methods define the actions that can be performed on or by the object. Familiarize yourself with these concepts and practice creating custom objects with properties and methods to enhance your skills for the exam. Understanding how to effectively define and use properties and methods will significantly improve your ability to model real-world entities in JavaScript.
2.5.3 Creating New Instances
Creating New Object Instances
In JavaScript, you can create new instances of custom objects using constructor functions or ES6 classes. Each instance is independent and has its own set of properties and methods.
Creating Instances Using Constructor Functions
Simple Example:
// Constructor function for creating Person objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.sayFullName = function() {
console.log(`Full Name: ${this.firstName} ${this.lastName}`);
};
}
// Creating new instances of Person
let person1 = new Person("Bob", "Smith");
let person2 = new Person("Alice", "Johnson");
person1.sayFullName(); // Output: Full Name: Bob Smith
person2.sayFullName(); // Output: Full Name: Alice Johnson
Complex Example:
// Constructor function for creating Car objects
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.getDetails = function() {
return `${this.year} ${this.make} ${this.model}`;
};
}
// Creating new instances of Car
let car1 = new Car("Toyota", "Camry", 2020);
let car2 = new Car("Honda", "Civic", 2021);
console.log(car1.getDetails()); // Output: 2020 Toyota Camry
console.log(car2.getDetails()); // Output: 2021 Honda Civic
Creating Instances Using ES6 Classes
Simple Example:
// Defining a class for Person
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
sayFullName() {
console.log(`Full Name: ${this.firstName} ${this.lastName}`);
}
}
// Creating new instances of Person
let person1 = new Person("Bob", "Smith");
let person2 = new Person("Alice", "Johnson");
person1.sayFullName(); // Output: Full Name: Bob Smith
person2.sayFullName(); // Output: Full Name: Alice Johnson
Complex Example:
// Defining a class for Car
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
getDetails() {
return `${this.year} ${this.make} ${this.model}`;
}
}
// Creating new instances of Car
let car1 = new Car("Toyota", "Camry", 2020);
let car2 = new Car("Honda", "Civic", 2021);
console.log(car1.getDetails()); // Output: 2020 Toyota Camry
console.log(car2.getDetails()); // Output: 2021 Honda Civic
Summary
Creating new instances of custom objects in JavaScript allows you to model real-world entities with their own properties and methods. You can use constructor functions for traditional object creation or ES6 classes for a more modern approach. Familiarize yourself with these methods and practice creating instances to enhance your skills for the exam. Understanding how to create and manage object instances is fundamental to effective JavaScript programming.
2.5.4 Creating Client-Side Arrays Using Custom Objects
Creating Client-Side Arrays
In JavaScript, you can create arrays of custom objects to store and manipulate multiple instances of the same object type. This is useful for managing collections of data in a structured way.
Example of Creating Client-Side Arrays with Custom Objects
Simple Example:
// Constructor function for creating Person objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.sayFullName = function() {
console.log(`Full Name: ${this.firstName} ${this.lastName}`);
};
}
// Creating an array to store multiple Person objects
let people = [];
// Adding Person objects to the array
people.push(new Person("Bob", "Smith"));
people.push(new Person("Alice", "Johnson"));
people.push(new Person("Charlie", "Brown"));
// Iterating over the array and calling the method for each Person
people.forEach(function(person) {
person.sayFullName();
});
Complex Example:
// Constructor function for creating Car objects
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.getDetails = function() {
return `${this.year} ${this.make} ${this.model}`;
};
}
// Creating an array to store multiple Car objects
let cars = [];
// Adding Car objects to the array
cars.push(new Car("Toyota", "Camry", 2020));
cars.push(new Car("Honda", "Civic", 2021));
cars.push(new Car("Ford", "Mustang", 2019));
// Iterating over the array and logging the details of each Car
cars.forEach(function(car) {
console.log(car.getDetails());
});
Summary
Creating client-side arrays using custom objects allows you to manage collections of related data effectively. By storing multiple instances of the same object type in an array, you can easily iterate over them, manipulate their properties, and call their methods. Familiarize yourself with this concept and practice creating and using arrays of custom objects to enhance your skills for the exam. Understanding how to work with arrays of objects is essential for building robust JavaScript applications.
2.5.5 Functions & Methods for Manipulating Arrays
Creating Functions for Manipulating Arrays
Functions can be created to perform various operations on client-side arrays, such as adding, removing, or updating elements.
Example of Creating Functions for Manipulating Arrays
Simple Example:
// Function to add a Person object to an array
function addPerson(peopleArray, firstName, lastName) {
let newPerson = new Person(firstName, lastName);
peopleArray.push(newPerson);
}
// Constructor function for creating Person objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.sayHello = function() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
};
}
// Creating an array to store Person objects
let people = [];
// Adding Person objects to the array
addPerson(people, "Bob", "Smith");
addPerson(people, "Alice", "Johnson");
// Calling sayHello on each Person in the array
people.forEach(function(person) {
person.sayHello();
});
Complex Example:
// Function to remove a Person object from an array by first name
function removePerson(peopleArray, firstName) {
const index = peopleArray.findIndex(person => person.firstName === firstName);
if (index !== -1) {
peopleArray.splice(index, 1);
console.log(`${firstName} has been removed from the array.`);
} else {
console.log(`${firstName} not found in the array.`);
}
}
// Using the previous Person constructor and people array
removePerson(people, "Alice"); // Output: Alice has been removed from the array.
people.forEach(function(person) {
person.sayHello(); // Output: Hello, my name is Bob Smith
});
Creating Methods for Manipulating Arrays
Methods can also be added to custom objects to perform operations specific to those objects.
Example of Adding Methods to Custom Objects
Simple Example:
// Adding a method to the Person constructor to list all people
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.sayHello = function() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
};
}
// Adding a method to the array of Person objects
Array.prototype.listPeople = function() {
this.forEach(function(person) {
person.sayHello();
});
};
// Creating an array to store Person objects
let people = [];
people.push(new Person("Bob", "Smith"));
people.push(new Person("Alice", "Johnson"));
// Calling the custom method to list all people
people.listPeople(); // Output: Hello, my name is Bob Smith
// Hello, my name is Alice Johnson
Complex Example:
// Adding a method to calculate the total number of people in the array
Array.prototype.totalPeople = function() {
return this.length;
};
// Using the previous people array
console.log(`Total number of people: ${people.totalPeople()}`); // Output: Total number of people: 2
Summary
Creating functions and methods for manipulating client-side arrays is essential for managing collections of data effectively. Functions can be used to perform operations such as adding, removing, or updating elements in an array, while methods can be added to custom objects to encapsulate behavior specific to those objects. Familiarize yourself with these concepts and practice creating functions and methods to enhance your skills for the exam. Understanding how to manipulate arrays and custom objects will significantly improve your ability to build dynamic JavaScript applications.
2.5.6 Using Prototype Property, Classes, Constructors, Iterators, and Generators
1. Using the Prototype Property
The prototype property allows you to add new properties and methods to existing constructors. This means that all instances of a constructor can share these properties and methods, promoting code reuse.
Simple Example: Adding a Method to the Prototype
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const alice = new Person('Alice');
alice.greet(); // Output: Hello, my name is Alice
Complex Example: Extending Built-in Objects
Array.prototype.last = function() {
return this[this.length - 1];
};
const numbers = [1, 2, 3, 4];
console.log(numbers.last()); // Output: 4
2. Using Classes and Constructors
ES6 introduced the class
keyword, which provides a clearer and more concise syntax for creating constructor functions and managing inheritance.
Simple Example: Defining a Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal('Dog');
dog.speak(); // Output: Dog makes a noise.
Complex Example: Inheritance with Classes
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const bulldog = new Dog('Bulldog');
bulldog.speak(); // Output: Bulldog barks.
3. Using Iterators and Generators
Iterators are objects that implement the iterator protocol, which consists of a next()
method that returns an object with value
and done
properties.
Simple Example: Creating an Iterator
function createIterator(array) {
let index = 0;
return {
next: function() {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { done: true };
}
}
};
}
const iterator = createIterator([1, 2, 3]);
console.log(iterator.next()); // Output: { value: 1, done: false }
console.log(iterator.next()); // Output: { value: 2, done: false }
console.log(iterator.next()); // Output: { value: 3, done: false }
console.log(iterator.next()); // Output: { done: true }
Complex Example: Using Generators
function* numberGenerator() {
let index = 0;
while (index < 3) {
yield index++;
}
}
const gen = numberGenerator();
console.log(gen.next()); // Output: { value: 0, done: false }
console.log(gen.next()); // Output: { value: 1, done: false }
console.log(gen.next()); // Output: { value: 2, done: false }
console.log(gen.next()); // Output: { done: true }
Summary
- Prototype Property: Allows adding methods and properties to constructors, enabling shared functionality.
- Classes and Constructors: ES6 syntax simplifies object-oriented programming and inheritance.
- Iterators and Generators: Iterators provide a way to traverse a collection, while generators allow for lazy evaluation and stateful function execution.
This guide should help you revise and understand the key concepts related to prototypes, classes, constructors, iterators, and generators in JavaScript. Familiarizing yourself with these concepts will enhance your ability to write efficient and organized code.