From 1e37becb55262cdd5fde99b741a4e080758c9025 Mon Sep 17 00:00:00 2001 From: Frank Espinoza Date: Fri, 9 Aug 2024 17:47:44 +0930 Subject: [PATCH] Add chapters on factory and constructor functions and dynamic objects This commit introduces new documentation sections explaining factory functions, constructor functions, the constructor property, and the dynamic nature of objects in JavaScript. These additions aim to enhance understanding of object creation and manipulation in JavaScript. --- en/SUMMARY.md | 4 + en/objects/constructor-functions.md | 95 ++++++++++++++++++++++ en/objects/constructor-property.md | 67 ++++++++++++++++ en/objects/dynamic-nature.md | 117 ++++++++++++++++++++++++++++ en/objects/factory-functions.md | 106 +++++++++++++++++++++++++ 5 files changed, 389 insertions(+) create mode 100644 en/objects/constructor-functions.md create mode 100644 en/objects/constructor-property.md create mode 100644 en/objects/dynamic-nature.md create mode 100644 en/objects/factory-functions.md diff --git a/en/SUMMARY.md b/en/SUMMARY.md index e17cc7fa..a3c47a93 100644 --- a/en/SUMMARY.md +++ b/en/SUMMARY.md @@ -64,6 +64,10 @@ - [Prototype](objects/prototype.md) - [Delete Operator](objects/delete.md) - [Enumeration](objects/enumeration.md) + - [Factory Functions](objects/factory-functions.md) + - [Constructor Functions](objects/constructor-functions.md) + - [Constructor Property](objects/constructor-property.md) + - [Dynamic Nature](objects/dynamic-nature.md) - [Date and Time](date-and-time.md) - [JSON](json.md) - [Error Handling](error-handling/README.md) diff --git a/en/objects/constructor-functions.md b/en/objects/constructor-functions.md new file mode 100644 index 00000000..1cdf4083 --- /dev/null +++ b/en/objects/constructor-functions.md @@ -0,0 +1,95 @@ +--- +chapter: 9 +description: Understanding Constructor Functions in JavaScript. +--- + +## Understanding Constructor Functions in JavaScript + +Constructor functions in JavaScript are special functions used to create and initialize objects. They provide a way to define a blueprint for creating multiple objects with similar properties and methods. + +### Defining a Constructor Function + +A constructor function is defined like a regular function but is typically named with an initial capital letter to distinguish it from regular functions. + +### Example of a Constructor Function + +Here's a basic example of a constructor function: + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const person1 = new Person("John", "Doe"); +const person2 = new Person("Jane", "Smith"); + +console.log(person1.firstName); // Output: John +console.log(person2.lastName); // Output: Smith +``` + +In this example, the `Person` constructor function initializes the `firstName` and `lastName` properties for each new object created. + +### Adding Methods to Constructor Functions + +You can add methods to the objects created by a constructor function by defining them on the constructor's prototype. + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +const person1 = new Person("John", "Doe"); +console.log(person1.getFullName()); // Output: John Doe +``` + +### Using `new` Keyword + +The `new` keyword is used to create an instance of an object from a constructor function. It performs the following steps: +1. Creates a new empty object. +2. Sets the `this` keyword to the new object. +3. Executes the constructor function. +4. Returns the new object. + +### Example with `new` Keyword + +```javascript +function Car(make, model) { + this.make = make; + this.model = model; +} + +const car1 = new Car("Toyota", "Corolla"); +console.log(car1.make); // Output: Toyota +``` + +### Constructor Functions vs. Classes + +ES6 introduced the `class` syntax, which provides a more concise and readable way to define constructor functions and methods. + +### Example with Classes + +```javascript +class Person { + constructor(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + getFullName() { + return `${this.firstName} ${this.lastName}`; + } +} + +const person1 = new Person("John", "Doe"); +console.log(person1.getFullName()); // Output: John Doe +``` + +### Conclusion + +Constructor functions are a fundamental feature in JavaScript for creating and initializing objects. They allow you to define a blueprint for objects and add methods to their prototype. With the introduction of ES6, the `class` syntax provides a more modern and readable way to achieve the same functionality. diff --git a/en/objects/constructor-property.md b/en/objects/constructor-property.md new file mode 100644 index 00000000..4f57b15d --- /dev/null +++ b/en/objects/constructor-property.md @@ -0,0 +1,67 @@ +--- +chapter: 9 +description: Understanding the `constructor` Property in JavaScript. +--- + +## Understanding the `constructor` Property in JavaScript + +The `constructor` property in JavaScript is a reference to the function that created an instance's prototype. It is a property of all objects that points to the function that was used to create the object. + +### What is the `constructor` Property? + +The `constructor` property returns a reference to the constructor function that created the instance. This is useful for identifying the type of an object. + +### Example of the `constructor` Property + +Here's a basic example to illustrate the `constructor` property: + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const person1 = new Person("John", "Doe"); +console.log(person1.constructor); // Output: [Function: Person] +``` + +In this example, the `constructor` property of `person1` points to the `Person` function. + +### Using the `constructor` Property to Create New Instances + +You can use the `constructor` property to create new instances of the same type: + +```javascript +const person2 = new person1.constructor("Jane", "Smith"); +console.log(person2.firstName); // Output: Jane +``` + +### `constructor` Property in Built-in Objects + +The `constructor` property is also available in built-in JavaScript objects: + +```javascript +const arr = []; +console.log(arr.constructor); // Output: [Function: Array] + +const obj = {}; +console.log(obj.constructor); // Output: [Function: Object] +``` + +### Modifying the `constructor` Property + +You can modify the `constructor` property, but it is generally not recommended as it can lead to unexpected behavior: + +```javascript +function Animal(name) { + this.name = name; +} + +const dog = new Animal("Rex"); +dog.constructor = Person; +console.log(dog.constructor); // Output: [Function: Person] +``` + +### Conclusion + +The `constructor` property is a useful feature in JavaScript that allows you to reference the function that created an instance's prototype. It can be used to identify the type of an object and create new instances of the same type. However, modifying the `constructor` property should be done with caution. \ No newline at end of file diff --git a/en/objects/dynamic-nature.md b/en/objects/dynamic-nature.md new file mode 100644 index 00000000..2a95c0b5 --- /dev/null +++ b/en/objects/dynamic-nature.md @@ -0,0 +1,117 @@ +--- +chapter: 9 +description: Understanding the Dynamic Nature of Objects in JavaScript. +--- + +## Understanding the Dynamic Nature of Objects in JavaScript + +JavaScript objects are dynamic, meaning their properties can be added, modified, or deleted at runtime. This flexibility +allows for powerful and adaptable code but requires careful management to avoid unexpected behavior. + +### Adding Properties + +You can add properties to an object at any time using dot notation or bracket notation. + +```javascript +const person = { + firstName: "John", + lastName: "Doe" +}; + +// Adding a new property +person.age = 30; +console.log( person.age ); // Output: 30 + +// Adding a property using bracket notation +person["gender"] = "male"; +console.log( person.gender ); // Output: male +``` + +### Modifying Properties + +Existing properties can be modified by reassigning their values. + +```javascript +const car = { + make: "Toyota", + model: "Corolla" +}; + +// Modifying a property +car.model = "Camry"; +console.log( car.model ); // Output: Camry +``` + +### Deleting Properties + +Properties can be removed from an object using the `delete` operator. + +```javascript +const book = { + title: "1984", + author: "George Orwell", + year: 1949 +}; + +// Deleting a property +delete book.year; +console.log( book.year ); // Output: undefined +``` + +### Checking for Properties + +You can check if an object has a specific property using the `in` operator or the `hasOwnProperty` method. + +```javascript +const user = { + username: "johndoe", + email: "john@example.com" +}; + +// Using the `in` operator +console.log( "email" in user ); // Output: true + +// Using `hasOwnProperty` method +console.log( user.hasOwnProperty( "username" ) ); // Output: true +``` + +### Iterating Over Properties + +You can iterate over an object's properties using a `for...in` loop. + +```javascript +const student = { + name: "Alice", + age: 22, + major: "Computer Science" +}; + +for (let key in student) { + if (student.hasOwnProperty( key )) { + console.log( `${key}: ${student[key]}` ); + } +} +// Output: +// name: Alice +// age: 22 +// major: Computer Science +``` + +### Dynamic Property Names + +You can use dynamic property names by using computed property names in object literals. + +```javascript +const propName = "score"; +const game = { + [propName]: 100 +}; + +console.log( game.score ); // Output: 100 +``` + +### Conclusion + +The dynamic nature of JavaScript objects provides great flexibility in managing data structures. You can add, modify, +and delete properties at runtime, check for the existence of properties, and iterate over them. This flexibility, while +powerful, requires careful handling to maintain code stability and predictability. \ No newline at end of file diff --git a/en/objects/factory-functions.md b/en/objects/factory-functions.md new file mode 100644 index 00000000..10721ca1 --- /dev/null +++ b/en/objects/factory-functions.md @@ -0,0 +1,106 @@ +--- +chapter: 9 +description: Understanding Factory Functions for Objects in JavaScript. +--- + +## Understanding Factory Functions for Objects in JavaScript + +Factory functions are functions that create and return objects. They provide a flexible way to create multiple instances of objects without using the `new` keyword or constructor functions. + +### Defining a Factory Function + +A factory function is a regular function that returns an object. It can include parameters to customize the properties of the created object. + +### Example of a Factory Function + +Here's a basic example of a factory function: + +```javascript +function createPerson(firstName, lastName) { + return { + firstName: firstName, + lastName: lastName, + getFullName: function() { + return `${this.firstName} ${this.lastName}`; + } + }; +} + +const person1 = createPerson("John", "Doe"); +const person2 = createPerson("Jane", "Smith"); + +console.log(person1.getFullName()); // Output: John Doe +console.log(person2.getFullName()); // Output: Jane Smith +``` + +In this example, the `createPerson` function returns a new object with `firstName`, `lastName`, and `getFullName` properties. + +### Advantages of Factory Functions + +1. **No `new` Keyword**: Factory functions do not require the `new` keyword, making them simpler and less error-prone. +2. **Encapsulation**: Factory functions can encapsulate private variables and methods. +3. **Flexibility**: They can return different types of objects based on conditions. + +### Encapsulation with Factory Functions + +Factory functions can encapsulate private data by defining variables inside the function scope and returning an object with methods that access those variables. + +```javascript +function createCounter() { + let count = 0; + return { + increment: function() { + count++; + return count; + }, + decrement: function() { + count--; + return count; + }, + getCount: function() { + return count; + } + }; +} + +const counter = createCounter(); +console.log(counter.increment()); // Output: 1 +console.log(counter.getCount()); // Output: 1 +console.log(counter.decrement()); // Output: 0 +``` + +### Returning Different Objects + +Factory functions can return different objects based on conditions, providing flexibility in object creation. + +```javascript +function createShape(type) { + if (type === "circle") { + return { + type: "circle", + radius: 10, + getArea: function() { + return Math.PI * this.radius * this.radius; + } + }; + } else if (type === "square") { + return { + type: "square", + side: 10, + getArea: function() { + return this.side * this.side; + } + }; + } +} + +const circle = createShape("circle"); +const square = createShape("square"); + +console.log(circle.getArea()); // Output: 314.1592653589793 +console.log(square.getArea()); // Output: 100 +``` + +### Conclusion + +Factory functions are a powerful and flexible way to create objects in JavaScript. They provide advantages such as avoiding the `new` keyword, encapsulating private data, and returning different types of objects based on conditions. By using factory functions, you can write more modular and maintainable code.