Creating JavaScript Objects with a constructor function

JavaScript objects can be created using a constructor function.

A constructor function uses the same syntax as a regular function, just the code placed between parentheses is different.
The way you access its content is also different that a regular function.

In the following example I am going to create a function named MyMotorbike and add properties within it.

Note:
Naming objects follow the same rules as naming functions and variables.


function MyMotorbike (model, engine, color) {
	this.model = model;
	this.engine = engine;
	this.color = color;
	}

The keyword this in JavaScript is used to represent the current object being used, this object so to speak.

Up to now we have the constructor function declared and the object’s properties set within the function.

A constructor function creates only the structure of an object, not a usable instance.
In order to use the object you have to create an instance of the object.
To create an instance of an object you have to use the JavaScript keyword new.


var MyHonda = new MyMotorbike ("PCX", "125cc", "Black");

The new variable that is created, MyHonda, is the new instance of the object MyMotorbike.
As you can see, the result of the MyMotorbike constructor function is assigned to the variable MyHonda.
The keyword new, placed after the equal sign, makes sure you are creating a new instance of the constructor function object.

The MyMotorbike function is called with values set as parameters.
These are the values used for this instance of the MyMotorbike object.
Given the order, the model is PCX, the engine is 125cc, and the color is black.

Now I can access the MyHonda instance of the MyMotorbike object. If I want to know what color is it painted then I can access it with the dot operator.


var PaintColor = MyHonda.color;

This assigns the value of the color property of MyHonda instance of the MyMotorbike object to the variable PaintColor.


//Declaring the conductor function MyComputer
function MyComputer(RAM,HardDrive,CPU) {
	this.RAM = RAM;
	this.HardDrive = HardDrive;
	this.CPU = CPU;
}

//Creating an instance of the conductor function MyComputer
var CustomizedComputer = new MyComputer("16GB","1TB","i7");

//Creating an independent variable that takes as value a property of the new instance object
var RAM_amount = CustomizedComputer.RAM;
var HardDrive_amount = CustomizedComputer.HardDrive;
var CPU_amount = CustomizedComputer.CPU;

document.write("I want " + RAM_amount + " of RAM memory, a hard drive with a capacity of " + HardDrive_amount + ", and an " + CPU_amount + " processor.");

Leave a Reply