About Lesson
JavaScript Constructor Functions
-
Creating Objects with the ‘new’ Keyword: Constructor functions are a special type of function that is used to create objects using the
new
keyword. -
Syntax:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.fullName = function() { return this.firstName + ” ” + this.lastName; }; }
const person1 = new Person(“John”, “Doe”);
* **`this` Keyword:**
- Inside a constructor function, `this` refers to the newly created object.
- Properties are assigned to the object using `this`.
* **Creating Objects:**
- When you use the `new` keyword with a constructor function:
1. A new empty object is created.
2. The constructor function is called with the `this` keyword bound to the newly created object.
3. The constructor function assigns properties and methods to the object using `this`.
4. The newly created object is returned.
* **Relationship to Classes:**
- Constructor functions are a precursor to the `class` syntax introduced in ES6.
- Classes provide a more modern and cleaner syntax for creating objects, but they essentially build upon the concept of constructor functions.
**In summary, constructor functions provide a structured way to create objects, making your code more organized and easier to maintain.**
**Note:** While constructor functions are still valid, the `class` syntax is generally preferred in modern JavaScript development due to its improved readability and maintainability.