Core JavaScript

Constructors

A constructor is a function that creates an object. An object is collection of associated variables and functions. These variables and functions are collected together because they are closely related. For example, the program below creates an animal object--I've called the type CAnimal-- with four member variables: msName, miLegs, mbHasHair, and mbIsACarnivore. These variables represent aspects of the created object and are sometimes called properties, attributes, or member variables. The functions are called methods or member functions. For simplicity and clarity, there are no member functions in this example.

The function that creates the object is called a constructor. The thing that it creates is called an object. The object that I create in the program represents a cat. The name CAnimal is the type or the class. To clarify, the class is the type and the object is an instance of the type. Just as I created the cat object below, I could create a dog, a horse, or any other animal object, which would all be of the type CAnimal.

The code below consists of an html file and a JavaScript code file. The html file is only used to call and execute the JavaScript code. In the JavaScript file, we begin with the CAnimal constructor function; notice that member variables are designated via the keyword "this" followed by a period. After the constructer, I create an object or instance of the CAnimal class that represents a cat. This object is created by using new with a call to the constructor function. Finally, we output the member variables to demonstrate how to access them.

Constructors.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="Constructors.js"></script>
</body>
</html>

Constructors.js

function CAnimal(sName,iLegs,bHasHair,bIsACarnivore) {
	this.msName = sName;
	this.miLegs = iLegs;
	this.mbHasHair = bHasHair;
	this.mbIsACarnivore = bIsACarnivore;
}

var qMyCat = new CAnimal("cat", 4, true, true);

document.write("Name = " + qMyCat.msName + "<br />");
document.write("Legs = " + qMyCat.miLegs + "<br />");
document.write("Has hair = " + qMyCat.mbHasHair + "<br />");
document.write("Is a carnivore = " + qMyCat.mbIsACarnivore + "<br />");
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.