Objects in JavaScript

Table of content:

What is a JavaScript object

A JavaScript object is an abstract entity that can be visualized as a real object that has features and properties.

Example:
JavaScript object → Abstract entity → real object → Honda PCX
Features → ABS break system
Properties → Mate black paint

You can break it down further by making the ABS break system have properties or you can go vice-versa by making the Honda PCX part of a bigger object as a parking lot.

A JavaScript object can contain other objects in it which they can contain other object too. Each of these objects can contain other objects with features and properties. Consider it as a family tree.

The main thing to remember here is that an object can hold a number of properties that you can access from outside and use in your script.

JavaScript objects allow you to organize things in your script differently. Instead of having a bunch or variable with values, now you can group them as features and properties of an object.
You can access these features with the use of dot operator which is just a dot or period.

For example, if you want the value of the paint property of the Honda PCX, you can access it with the following line:


var HondaType = motorbike.paint;

The object is written first then it is connected to its property you want to access by a dot.

How to create objects in JavaScript

Before starting to create objects you need to know how to name and how to structure them. You also need to know how to include methods in your objects.

Naming JavaScript Objects

Naming objects follow the same rules as naming functions and variables. Objects’ names are case sensitive and when naming them you have to avoid reserved words/objects. You can take a look at Variables and Functions to learn more about naming in JavaScript.

Structuring JavaScript Objects

JavaScript objects can be created in two ways: using a constructor function or using an object initializer.

Constructor functions

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.


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 use 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 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.

Example


//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.");

Object initializer

An object initializer is a little shorter than a constructor function. The following is the syntax of an object initializer.


MyMotorbike = {engine:125cc}

Pretty simple! MyMotorbike is the object name, engine is the property, and 125cc is the value of the property.

One important thing to be remembered is that an object created with the initializer function is already an instance of the object so the properties can be used without creating a new instance of the object.

Next, we are going to create an object called MyComputer using the initializer method. It’s going to have three sets of properties and values.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}

Since there is no need to create an instance of the object we can use its properties to assign them to variables or write them to the page. We can even create more obejcts.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}
MyNextComputer = {CPU:"i7" , RAM:"16GB" , SSD:"512GB"}

Next I can write what I want my next computer to be using these properties.


MyComputer = {CPU:"i5" , RAM:"8GB" , SSD:"120GB"}
MyNextComputer = {CPU:"i7" , RAM:"16GB" , SSD:"512GB"}
document.write("Right now my computer has an "+MyComputer.CPU+" processor,
"+MyComputer.RAM+" of RAM memory, and a "+MyComputer.SSD+" Solid State Drive.");
document.write("But, my next computer is going to have an "+MyNextComputer.CPU+
" processor, "+MyNextComputer.RAM+" of RAM memory, and a "+MyNextComputer.SSD+" Solid State Drive.");

Adding methods

A method is a function call that is part of an object and can perform various tasks, as any other function could, that you want to execute with the properties of the object. Example:


function HowMuchIf() {

var ThePrice = 1000;

if(this.CPU == "i7") {
ThePrice += 100;
}
else {
ThePrice += 50;
}

if(this.RAM == "16GB") {
ThePrice += 50;
}
else {
ThePrice += 25;
}

if(this.SSD == "256GB") {
ThePrice += 150;
}
else {
ThePrice += 100;
}

return ThePrice;

}

This function is quiet long, let’s shorten it with the conditional operator.


function HowMuchIf() {
var ThePrice = 1000;
ThePrice += (this.CPU == "i7") ? 100 : 50;
ThePrice += (this.RAM == "16GB") ? 50 : 25;
ThePrice += (this.SSD == "256GB") ? 150 : 100;
return ThePrice;
}

Next step is to assign the function to the object within the object constructor function.


function MyCustomizedComputer (CPU, RAM, SSD) {
this.CPU=CPU;
this.RAM=RAM;
this.SSD=SSD;
this.HowMuch=HowMuchIf;
}

The above code defines a method named HowMuch that calls the HowMuchIf() function. When the function is called the parentheses are not used. That’s because we want the function itself not the result of it. This how the function becomes a method of the object.

Next step is to create an instance of the object.


var DanComputer = new MyCustomizedComputer ("i5", "8GB", "120GB");
var SoniaComputer = new MyCustomizedComputer ("i7", "16GB", "256GB");
var GamingComputer = new MyCustomizedComputer (DanComputer.CPU, SoniaComputer.RAM, DanComputer.SSD);

Up to now we have the function HowMuchIf() that creates HowMuch method of the MyCustomizedComputer object, the HowMuch method within the MyCustomizedComputer object, and three instances of the MyCustomizedComputer object.

To find the value of DanComputer we have to call HowMuch method. We use the same method for the other two instances.


var DanComputer_value = DanComputer.HowMuch();
var SoniaComputer_value = SoniaComputer.HowMuch();
var GamingComputer_value = GamingComputer.HowMuch();

Now we need to print this on the screen so we can see the price of these computers.


document.write (DanComputer_value);
document.write (SoniaComputer_value);
document.write (GamingComputer_value);

So, what we have at the end is the following


//The function that is used as a method
function HowMuchIf() {
var ThePrice = 1000;
ThePrice += (this.CPU == "i7") ? 100 : 50;
ThePrice += (this.RAM == "16GB") ? 50 : 25;
ThePrice += (this.SSD == "256GB") ? 150 : 100;
return ThePrice;
}

/*
The constructor function which makes the above function a method function
MyCustomizedComputer ... is an object
HowMuch ... is a method
HowMuchIf ... is a function method
*/
function MyCustomizedComputer (CPU, RAM, SSD) {
this.CPU=CPU;
this.RAM=RAM;
this.SSD=SSD;
this.HowMuch=HowMuchIf;
}

/*
These are instances of MyCustomizedComputer object
*/
var DanComputer = new MyCustomizedComputer ("i5", "8GB", "120GB");
var SoniaComputer = new MyCustomizedComputer ("i7", "16GB", "256GB");
var GamingComputer = new MyCustomizedComputer (DanComputer.CPU, SoniaComputer.RAM, DanComputer.SSD);

/*
Use the method HowMuch (which is the result of HowMuchIf function)
to find the value of DanComputer
The same applies for the other two instances
*/
var DanComputer_value = DanComputer.HowMuch();
var SoniaComputer_value = SoniaComputer.HowMuch();
var GamingComputer_value = GamingComputer.HowMuch();

//Print on the screen
document.write (DanComputer_value);
document.write (SoniaComputer_value);
document.write (GamingComputer_value);

Object manipulation statements

You can use foor-in loop and with statement to access and manipulate your objects easily.

The for-in loop

The for-in loop allows you to cycle through the properties of an object to display or manipulate their values.


for (var variable_name in object_name) {
JavaScript statements go here
}

For example, if you want to cycle through the properties of an instance of MyCustomizedComputer object in order to display the values on the screen then using for-in loop is a time saver since you don’t have to type each property name.


//This is the object
function MyCustomizedComputer (CPU, RAM, SSD) {
this.CPU=CPU;
this.RAM=RAM;
this.SSD=SSD;
}

//This is the new instance
var DanComputer = new MyCustomizedComputer ("i5", "8GB", "120GB");

//This is for-in loop
for (var DisplayProperties in DanComputer) {
document.write (DanComputer [DisplayProperties] );
}

Notice DanComputer[DisplayProperties] which is unfamiliar. It is an array to store the properties values.

The with statement

The with statement allows you to access or manipulate the properties and methods of an object easily if you want to use a large number of statements that use the object.

For example, the with statement allows you to leave off the object name and the dot operator for statements inside the with block so you only need to type the property name to access it.


function MyCustomizedComputer (CPU, RAM, SSD) {
this.CPU=CPU;
this.RAM=RAM;
this.SSD=SSD;
}

var DanComputer = new MyCustomizedComputer ("i5", "8GB", "120GB");

with (DanComputer) {
document.write("CPU: "+CPU);
document.write("RAM: "+RAM);
document.write("SSD: "+SSD);
}

Predefined JavaScript Objects

There are many predefined objects in JavaScript that you can use to get access to certain properties or methods that you may need. We are going to look at two of these predefined JavaScript objects which are The Navigator Object and The History Object.

The Navigator Object

The Navigator object gives you access to various properties of the viewer’s browser (name, version number etc). The navigator object is part of the window object which means that you can access its properties and methods using window.navigator. property_or_method_name. It can be shortened to navigator. property_or_method_name.

For example instead of window.alert(“hi!”); we can have alert(“hi!”);.

Properties of the navigator object

The properties of the navigator object allows you to find various things about the browser used by the viewers. These properties can not be changed because they are set to be read-only but you can find what the value of the property is and use it in your script accordingly.

Below is the table of the properties of the navigator objects and their returned values.

Property Value
AppCodeName The code name of the browser.
appName The name of the browser.
appMinorVersion A string representing a minor version of the browser (IE only).
appVersion The version of the browser and some other information.
browserLanguage The language of the browser being used. (IE and Opera)
buildID The build identifier of the browser. (Firefox only)
cookieEnabled Specifies whether or not the browser has cookies enabled.
cpuClass A string representing the class of the CPU. (IE only)
language The language of the browser being used. (Firefox and Opera)
mimeTypes An array of MIME types supported by the browser.
onLine Specifies whether or not the browser is in “global offline mode”.
oscpu A string representing the operating system of the computer. (Firefox only)
platform The machine type for which the browser was created.
plugins An array of the plugins the browser has installed on it.
product A string representing the product name of the browser being used. (Firefox only)
productSub The build number of the browser being used. (Firefox only)
securityPolicy An empty string-returned a value in Netscape 4.7. (Firefox only)
systemLanguage The default language used by the operating system. (IE only)
userLanguage The natural language of the operating system. (IE and Opera)
userAgent The user agent header for the browser.
vendor An empty string-returned a string representing the vendor of the browser being used. (Firefox only)
vendorSub An empty string-returned the vendor version number of the browser being used. (Firefox only)

appCodeName Property

This property holds the value of the application code name of the browser.


window.alert("You are using "+navigator.appCodeName);

Most browsers will return “You are using Modzilla” which was used as the code name for an early version of Netscape Navigator.

appName Property

The appName property allows you to find out which type of browser the viewer is using to view the page.


window.alert("You are using "+navigator.appName);

Using the appName property you can create a browser detection script that allows you to send the viewer an alert about your opinion of the browser being used.


switch(navigator.appName) {
case "Netscape": window.alert("Netscape/Firefox is a great browser."); break;
case "Microsoft Internet Explorer": window.alert("IE is cool"); break;
case "Opera": window.alert("Opera is a great browser"); break;
default : window.alert("What browser are you using?");
}

appVersion Property

The appVersion property has a value of the version number of the browser being used and some additional information. This can be useful when you use techniques that should only be executed in browser versions above a certain level.


window.alert("You are using "+navigator.appVersion);

cookieEnabled Property

The cookieEnabled property returns a Boolean value of true if cookies are enabled in the browser and false if they are not.

onLine Property

The onLine property returns a Boolean value of true if the viewer system is not in “global offline mode” and false if it is.

platform Property

The platform property holds a value of the type of machine for which the browser was created.


window.alert("You are using "+navigator.platform);

It can be useful if you want to redirect viewers to a different page based on their machine type.

plugins Property

This array holds the values of all plugins installed in the viewer’s browser.

userAgent Property

The userAgent property gives you a long string of information about the browser being used. This string is the user agent header for the browser.


window.alert("You are using "+navigator.userAgent);

In my case, the code above returnes “You are using Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0”.

Methods of the navigator object

The navigator object has a number of methods you can use to performe various tasks. Below is the table of available methods in the navigator object.

Method Purpose
javaEnabled() Tests whether or not Java is enabled in the browser.
mozIsLocallyAvailable() Checks if a file at a certain address is locally available (Firefox only).
preference() Allows certain browser preferances to be set (requires signed script).
registerContentHandler() Allows a website to set itself as a potential handler of a certain MIME type.
registerProtocolHandler() Allows a website to set itself as a potential handler of a certain protocol.

javaEnabled() method

The javaEnabled() method checks if the viewer has Java enabled or not in the browser and returns a value of true (if enabled) of false (if not enabled). Example:


var JavaIsOn = navigator.javaEnabled();
if (JavaIsOn == true) {
window.alert("Java is enabled! That's great!");
}
else {
window.alert("Java is not enabled! You can't see my Java applet!");
}

The History Object

The history object is also part of the window object and it provides information about the browser history of the current window.

Property of the History Object

The history object has only one property which is called lenght. The lenght property returns the number of pages in the session history of the browser for the current window (including the currently loaded page).
Example:


alert("You viewed "+history.length+" page(s).");

Methods of the History Object

The table below shows the three methods available for the history object.

Method Purpose
back() Sends the browser window one page back in the history list.
forward() Sends the browser window one page forward in the history list.
go() Sends the browser to a specified page in the history list using an integer value.

The back() Method

The back() method sends the browser to the last page visited in the history list before the curent page. It is similar to the browser “back” button. Example:


<form>
<input type="button" value="Back" id="go-back" />
</form>

<script type="text/javascript">
var BackButton = document.getElementById("go-back");
BackButton.onclick = function() {
history.back();
}
</script>

The forward() Method

The forward() method sends the browser to the page visited in the history list after the current page. To use it you call the method in the script where desired. As example, let’s update the previous script with a forward button:


<form>
<input type="button" value="Back" id="go-back" />
<input type="button" value="Forward" id="go-forward" />
</form>

<script type="text/javascript">
var BackButton = document.getElementById("go-back");
var ForwardButton = document.getElementById("go-forward");

BackButton.onclick = function() {
history.back();
}
ForwardButton.onclick = function() {
history.forward();
}
</script>

The go() Method

The go() method takes in an integer as a parameter. The integer can be a positive number to go forward in the history list or a negative number to go back in the history list.


history.go(3);

The abobe code will go forward three pages in the window’s history.


history.go(-4);

The abobe code will go back four pages in the window’s history.

Leave a Reply