Home >Web Front-end >JS Tutorial >How Do You Create Constructors in JavaScript Objects?

How Do You Create Constructors in JavaScript Objects?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 18:03:02820browse

How Do You Create Constructors in JavaScript Objects?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn