Home > Article > Web Front-end > How Do You Create Constructors in JavaScript Objects?
JavaScript objects can have constructors. Unlike other programming languages, JavaScript does not use a special keyword like constructor to define a constructor. Instead, constructors are created using prototypes.
Creating Constructors with Prototypes:
In this approach, a constructor function is created with a capitalized name. Inside the constructor, the properties of the object are assigned using the this keyword. To access the properties and methods of all objects created using this constructor, a prototype is created. The prototype can contain methods and properties that will be inherited by all objects created from this constructor.
<code class="javascript">function Box(color) // Constructor { this.color = color; } Box.prototype.getColor = function() { return this.color; };</code>
In this example, the constructor Box accepts a parameter color and assigns it to the color property of the object. The prototype of the Box constructor defines a method called getColor that returns the color property of the object.
Hiding Private Members:
To hide properties from external access, a variable can be declared inside the constructor function and accessed only through a method. This is not a true private member, but it offers some form of encapsulation.
<code class="javascript">function Box(col) { var color = col; this.getColor = function() { return color; }; }</code>
In this example, the color property is declared as a variable inside the constructor and is inaccessible outside the constructor. The getColor method provides access to the color property.
Usage:
To create objects using the constructor, the new keyword is used. The following code shows the usage of constructors:
<code class="javascript">var blueBox = new Box("blue"); alert(blueBox.getColor()); // will alert blue var greenBox = new Box("green"); alert(greenBox.getColor()); // will alert green</code>
The above is the detailed content of How Do You Create Constructors in JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!