JavaScript Constructor Functions
Explore how JavaScript constructor functions serve as blueprints for creating custom objects with properties and methods. Understand object creation with the new keyword, use of 'this' keyword, and how prototype objects enable shared behaviors among instances. Gain foundational knowledge for effective object-oriented programming in JavaScript.
We'll cover the following...
Background
We know what OOPs are and their class-based and/or prototype-based approach. The challenge when using OOPs is creating a general mechanism to generate custom objects. In this lesson, we will use functions to construct objects, also called constructor functions. This is the best approach to implement prototype-based OOPs.
Constructor functions
Constructor functions, or object constructor functions, contain blueprints to a type of object that has properties and methods to generate objects. All objects created from a constructor function will have the same properties and methods but not necessarily the same values.
Syntax
Let’s look at the syntax of a constructor function.
As we can see from above:
-
The keyword
functiondefines the function. -
The constructor function name should be capitalized, as per convention, just like
FunctionNamein the ...