JavaScript Window Navigator

In this chapter you will learn about JavaScript Window Navigator object. We can use the navigator object to get the browser related information.

Window Navigator Object

It is not mandatory to put window object before the navigator object. You can access navigator object without the window object.

Check Cookie enabled

The navigator object cookieEnabled property returns true if cookies are enabled on the client browser, otherwise it will return false.

Example

<!DOCTYPE html>
<html>
<body>

Window Navigator object is used to check if browser accepts cookies or not.
<p id="test"></p>

<script>
var ce = (navigator.cookieEnabled) ? 'Enabled' : 'disabled';
document.getElementById("test").innerHTML = "Cookies is " + ce;
</script>

</body>
</html>

Download the code Run the code

Browser Name

Navigator object appName and appCodeName properties returns name of the browser.

<!DOCTYPE html>
<html>
<body>

appName and appCodeName properties returns browser app name and code name.
<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your Browser app name is " + navigator.appName + ' and code name is ' + navigator.appCodeName;
</script>

</body>
</html>

Download the code Run the code

Note

IE11, Chrome, Firefox, and Safari browsers return “Netscape” as appName value.
Chrome, Firefox, IE, Safari, and Opera browsers return “Mozilla” as appCodeName value.

Browser Engine

Navigator object product property returns engine name of the browser.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your browser engine is " + navigator.product;
</script>

</body>
</html>

Download the code Run the code

Browser Version

Navigator object appVersion property returns browser version information.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your Browser version is " + navigator.appVersion;
</script>

</body>
</html>

Download the code Run the code

userAgent property also returns browser information.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your Browser version is " + navigator.userAgent;
</script>

</body>
</html>

Download the code Run the code

The information retrieved from the navigator object can be misleading, and should be avoided to detect browser versions because:

  • Different browsers might have same browser names. For example IE11, Chrome has same name.
  • Navigator data can be changed by external extensions.

Browser Platform

Navigator object platform property returns browser operating system.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your Browser running on " + navigator.platform;
</script>

</body>
</html>

Download the code Run the code

Browser Language

Navigator object language property returns browser’s language.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
document.getElementById("test").innerHTML = "Your Browser language is " + navigator.language;
</script>

</body>
</html>

Download the code Run the code

Java Enabled?

Navigator object javaEnabled() methods returns if Java is enabled or not.

<!DOCTYPE html>
<html>
<body>

<p id="test"></p>

<script>
if(navigator.javaEnabled()) {
    document.getElementById("test").innerHTML = "Java is enabled on your Browser.";
} else {
    document.getElementById("test").innerHTML = "Java is disabled on your Browser.";
}

</script>

</body>
</html>

Download the code Run the code

JavaScript History

In this chapter you will learn about JavaScript Window History object(window.history). The history object contains browser history.

Window History Object

It is not mandatory to prefix window object with history object. It can be write without window object.

There are some limitations to access history object due to privacy and security of user.

Methods

history.back() – same as when click on back button in the browser
history.forward() – same as when click on forward forward button in the browser
history.go() – allows to move more than one step backward or forward

History Back Method

The history.back() method is use for the previous URL from the browser History list.

This action is same as clicking on browser back button.

Example

<html>
<head>
<script>
function previousPage() {
    window.history.back()
}
</script>
</head>
<body>

<input type="button" value="Click to go Back" onclick="previousPage()">

</body>
</html>

Above code display a button “Click to go Back”, when click on this button, it is similar to click on a browser back button event.

History Forward Method

The history.forward() method is use for the next URL from the browser History list.

This action is same as clicking on browser forward button.

Example

<html>
<head>
<script>
function nextPage() {
    window.history.forward()
}
</script>
</head>
<body>

<input type="button" value="Click to go Forward" onclick="nextPage()">

</body>
</html>

Above code display a button “Click to go Forward”, when click on this button, it is similar to click on a browser forward button event.

Go to a specific page from history

You can use history.go() method to go to specific page of browser history. This method accepts both positive and negative values. Current page index is set to 0.

history.go(-1);
history.go(1);

Note than history methods works only if there are entries available in browser history.

You can count the number of pages available in the history by using the value of the length property of history object.

var historyCount = window.history.length;

It is always check for history length before using other methods.

JavaScript Location Object

In this chapter you will learn about JavaScript location object. The location object can be use to get the current page URL and to redirect the browser to a new page or reload current page.

Window Location Object

It is not mandatory to prefix window object with location object. It can be write without window object.

Example

  • location.href returns the current page URL
  • location.hostname returns the domain name of the current page
  • location.pathname returns the path and file name of the current page
  • location.protocol returns the protocol(http or https) of the current page
  • location.port return the port number in use.

Location Href

The location.href returns the URL of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.href displays current page URL.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.href;
</script>

</body>
</html>

Download the code Run the code

Location Hostname

The location.hostname returns the domain name of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.hostname displays current page domain name or host name with port (if specified in URL)
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.hostname;
</script>

</body>
</html>

Download the code Run the code

Location Pathname

The location.pathname returns the pathname of the current web page. In URL, anything after domain name starting with slash(/) is called pathname.

http://www.example.com/extra/location/add.php
In above URL, /extra/location is path name

Example

<!DOCTYPE html>
<html>
<body>

location.pathname displays current page path name.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.pathname;
</script>

</body>
</html>

Download the code Run the code

As current page has no pathname set, it returns only / as pathname.

Location Protocol

The location.protocol returns the used protocol of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.protocol displays current page protocol. It can be either http: or https:.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.protocol;
</script>

</body>
</html>

Download the code Run the code

Location Hash

The location.hash returns the hash value of the current web page URL. Any value from URL after the # character is hash value. Location Hash value is mostly use for to keep page position after page reload for Ajax content.

Example

<!DOCTYPE html>
<html>
<body>

location.hash displays hash part of current URL.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.hash;
</script>

</body>
</html>

Download the code Run the code

JavaScript Cookies

JavaScript Cookies allows you to store data on web page.

What are JavaScript cookies?

Cookies are data stored in small files on a user’s computer.

When a request is completed by web server, the connection with the server is terminated and there is no information of user with the server.

Cookies are use to remember the user data.

When a user visits a web page, user information for example say user’s total visit on web page is stored in a cookie. When user visits the web page next time, it shows user’s total visits from cookie data.

Cookies are store as a name value pair.

totalvisits = 3;

When a browser requests a webpage from a server, all cookies relate to that domain is sent with the request. Hence server can get data of cookies.

Create cookies

JavaScript can create, read, modify or delete cookies. JavaScript uses document.cookie property for this.

Using JavaScript cookies can be create as below.

document.cookie = "totalvisits=3";

You can add cookie expire time when creating a new cookie. Expire time must be in UTC format. If expire time is not provided, it will delete when browser is close.

document.cookie = "totalvisits=3; expires=Sun, 25 Dec 2016 12:00:00 UTC";

There is a path parameter using it, you can define the cookie belongs to which page. If path parameter is not set, cookie is set for current page.

document.cookie = "totalvisits=3; expires=Sun, 25 Dec 2016 12:00:00 UTC; path = /";

Read Cookie

You can read cookies using JavaScript as below:

var c=document.cookie;

Above statement returns all the cookie belongs to current page.

Modify Cookie

You can modify cookies same way you can create a cookie. If cookie is create with same name as existing cookie it will replace old cookie.

document.cookie = "totalvisits=4; expires=Sun, 25 Dec 2016 12:00:00 UTC; path = /";

Delete a Cookie

It is easy to delete cookie. To delete cookie just set cookie expire time in past.

document.cookie = "totalvisits=4; expires=Thu, 01 Jan 1970 00:00:00 UTC; path = /";

Cookie String

Cookie value looks like normal string.

If you create a new cookie, old cookies are not overwritten, but new cookie is append to old cookie string.

There is no direct way to access one cookie value, you should create custom function to retrieve one cookie value.

Cookie Example

First time user visits page, we will store its visit count to cookie. When user visits next time we will check if user has visited a page before, if so than retrieve value of user visit count, increment it and store it again in cookie.

We will create below functions.

  • Set: A function to set a cookie value
  • Get: A function to get a cookie value
  • Check: A function to check a cookie value

A Function to Set a Cookie

First we will create a function to set a new cookie.

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

In above function, cname is cookie name, cvalue is cookie value and exdays is cookie expiry in days.

A Function to Get a Cookie

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
} 

Above function retrieve cookie value based on given cookie name. It splits cookie string with semicolon(;) and retrieve all cookies in an array. Than it compares cookie name within array. Once match is found it retrieve its value and return it.

A Function to Check a Cookie

function checkCookie() {
    var visits=getCookie("totalvisit");
    if (visits!="") {
        setCookie("totalvisit", (parseInt(visits)+ 1), 365);
        alert("Total visits " + visits);
    } else {
        setCookie("totalvisit", 1, 365);
    }
} 

Complete Example

<!DOCTYPE html>
<html>
<body>

Display the pixel depth of the screen:
<p id="screencolor"></p>

<script>
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
} 

function checkCookie() {
    var visits=getCookie("totalvisit");
    if (visits!="") {
        setCookie("totalvisit", (parseInt(visits) + 1), 365);
        alert("Total visits " + visits);
    } else {
        setCookie("totalvisit", 1, 365);
		alert("You visited for the first time.");
    }
} 

checkCookie();
</script>

</body>
</html>

Download the code Run the code

JavaScript Window Screen

In previous chapter you learn about JavaScript Window object. In this chapter you will learn about window screen.

You can get user’s screen information using JavaScript window screen object. This properties can be use to improve user experience of user based on its screen details.

Window Screen

It is not mandatory to write window prefix with screen object. It can be written without window prefix

Properties of Window Screen object

  • screen.width
  • screen.height
  • screen.availWidth
  • screen.availHeight
  • screen.colorDepth
  • screen.pixelDepth

Window Screen Width

You can use JavaScript screen.width property to determine the client browser’s screen width in pixels.

Example

<!DOCTYPE html>
<html>
<body>

<p id="screenwidth"></p>

<script>
document.getElementById("screenwidth").innerHTML = "Your Screen Width: " + screen.width;
</script>

</body>
</html>

Download the code Run the code

Window Screen Height

You can use JavaScript screen.height property to determine the client browser’s screen height in pixels.

Example

<!DOCTYPE html>
<html>
<body>

<p id="screenheight"></p>

<script>
document.getElementById("screenheight").innerHTML = "Your Screen Height: " + screen.height;
</script>

</body>
</html>

Download the code Run the code

Available Screen Width

You can use JavaScript screen.availWidth property to determine the client browser’s screen available width in pixels without windows taskbar.

Example

<!DOCTYPE html>
<html>
<body>

<p id="screenwidth"></p>

<script>
document.getElementById("screenwidth").innerHTML = "Your Available Screen Width: " + screen.availWidth;
</script>

</body>
</html>

Download the code Run the code

Available Screen Height

You can use JavaScript screen.availHeight property to determine the client browser’s screen available height in pixels without windows taskbar.

Example

<!DOCTYPE html>
<html>
<body>

<p id="screenheight"></p>

<script>
document.getElementById("screenheight").innerHTML = "Your Available Screen height: " + screen.availHeight;
</script>

</body>
</html>

Download the code Run the code

Screen Color Depth

The screen.colorDepth property is use to determine the number of bits used to display one color.

Now a days all modern computers use 24 bit or 32 bit hardware for color resolution:

  • 24 bits = 16,777,216 different “True Colors”
  • 32 bits = 4,294,967,296 different “Deep Colors”

Older computers used 16 bits: 65,536 different “High Colors” resolution. Very old computers used only bits which results in only 256 different VGA colors only.

Example

document.getElementById("screencolor").innerHTML = "Your Screen Color depth: " + screen.colorDepth;

Screen Pixel Depth

You can use screen.pixelDepth property to deter mine pixel depth of screen.

Example

document.getElementById("screencolor").innerHTML = "Your Screen Color depth: " + screen.pixelDepth;

In modern computer systems, color depth and pixel depth properties are equal.

JavaScript Object Methods

In previous chapter you learn about object properties, in this chapter you will learn about object methods, how to create object methods.

The actions that can be perform on objects are called JavaScript Object methods.

Basically a JavaScript method is a property of an object with function definition as value.

var car = {
    make : 'Audi',
    model : 'A4',
    year : '2007',
    manufacturer : function() {
        return this.make+' '+this.model;
    }
};

Access Object Methods

You can create an object method using below syntax.

Syntax

 methodName : function() { code lines } 

Like object properties, object methods are also accessible using dot(.) with object name.

car.manufacturer()

Since methods are one type of property, manufacturer() is describe as an object method and manufacturer is describe as object property.

When manufacturer property will execute as a function when it is invoke using ().

Below example accesses the manufacturer() method of a car object.

<!DOCTYPE html>
<html>
<body>

Define and use of object methods.

<p id="text"></p>

<script>
var car = {
    make : 'Audi',
    model : 'A4',
    year : '2007',
    manufacturer : function() {
        return this.make+' '+this.model;
    }
};

document.getElementById("text").innerHTML = 'Car make-model : ' + car.manufacturer();
</script>

</body>
</html>

Download the code Run the code

If somehow the manufacturer property is access without () than it returns function definition.

<!DOCTYPE html>
<html>
<body>

Define and use of object methods.
When () is missed, it will return function definition.
<p id="text"></p>

<script>
var car = {
    make : 'Audi',
    model : 'A4',
    year : '2007',
    manufacturer : function() {
        return this.make+' '+this.model;
    }
};

document.getElementById("text").innerHTML = car.manufacturer;
</script>

</body>
</html>

Download the code Run the code

Built-in methods

There are many inbuilt methods available with default objects. For example below code uses toLowerCase() method of a String object to convert text to lower case.

<!DOCTYPE html>
<html>
<body>

There are many built in methods available
<p id="text"></p>

<script>
var manufacturer = 'Audi A4';
var lower = manufacturer.toLowerCase();

document.getElementById("text").innerHTML = lower;
</script>

</body>
</html>

Download the code Run the code

The value of variable lower after string operation will be:

audi a4

Add new methods

Object Methods are define in constructor function.

<!DOCTYPE html>
<html>
<body>

There are many built in methods available
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.changeMake= function(make) {return this.make=make;};
}

var car = new Vehicle('BMW', '116', '2005', 'Red');
document.getElementById("text").innerHTML = 'Car make is '+ car.changeMake('Toyota');
</script>

</body>
</html>

Download the code Run the code

You will learn more about methods in next chapter Object Prototype. For example how to add new methods to an existing object and how to add new methods after prototype constructor function is defined.

JavaScript Window Object

JavaScript Window – The Browser Object Model

The Browser Object Model shortly refer as BOM allows JavaScript to interact with Browser(Window Object).

The Browser Object Model

There is no any specific official standard for the Browser Object Model(BOM).

Since all modern browsers have almost the same standards(methods and properties) to JavaScript interactivity, it is refer to the properties of BOM.

The Window Object

All browser has support for Window object. It refer to the current open browser’s window.

The Window object is parent of all, so all global JavaScript functions, methods, variables and objects automatically become member of Window object.

All global variables becomes properties of a Window.

Same applies to global methods and functions, they become methods of window.

There is only one instance of Window object at a time.

The window object is top of all objects, even Document object (DOM) is also property of it.

window.document.getElementById("header");

Above statement can be rewrite as

document.getElementById("header");

Often window word is ignored from the statements as shown above.

Window Size

You can get size(width and height) of window using window object.
There are two properties which can be used to get window size.

Both properties to get window size returns size in pixels.

  • window.innerHeight – inner height of the browser window (in pixels)
  • window.innerWidth – inner width of the browser window (in pixels)

Both properties ignore window toolbar and window scroll-bar height & width as its not part of window view-port.

For old versions of Internet explorer 5,6,7,8 there are different properties

  • document.documentElement.clientHeight
  • document.documentElement.clientWidth

or

  • document.body.clientHeight
  • document.body.clientWidth

Below example illustrates browser independent height and width of window.

Example

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>
var ww = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var wh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

document.getElementById("text").innerHTML = "Browser window dimention width: " + ww + ", height: " + wh + ".";
</script>

</body>
</html>

Download the code Run the code

Above example displays the browser window’s height and width. Try it resizing browser to see different results.

Other Window Methods

Below are some other window methods.

  • window.open() – open a new window
  • window.close() – close the current window
  • window.moveTo() -move the current window
  • window.resizeTo() -resize the current window

JavaScript Object Properties

Object Properties

Properties are the most important part of JavaScript object.

JavaScript Properties

Properties are the values in an Object. An object is a combination of properties. Properties in an Object can be in any order.

Properties can be add, modify or delete from an object but some properties can be readonly.

Accessing Object Properties

JavaScript properties can be access in many ways.

 objectName.property          // car.make

or

 objectName["property"]       // car["make"]

or

 objectName["expression"]       // x = make; car[x]

Expression value must evaluates to valid property name.

Example

<!DOCTYPE html>
<html>
<body>

Object properties can be access using either .property or [property]
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}

Vehicle.prototype.sub_type = "Sedan";

var car = new Vehicle('Audi', 'A4', '2009', 'Red');

document.getElementById('text').innerHTML = 'Car manufacturer is ' + car.make + ' ' + car.model;
</script>

</body>
</html>

Download the code Run the code

Example

<!DOCTYPE html>
<html>
<body>

Object properties can be access using either .property or [property]
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}

Vehicle.prototype.sub_type = "Sedan";

var car = new Vehicle('Audi', 'A4', '2009', 'Red');

document.getElementById('text').innerHTML = 'Car manufacturer is ' + car['make'] + ' ' + car['model'];
</script>

</body>
</html>

Download the code Run the code

JavaScript for…in Loop

The JavaScript for…in loop statement is use to loop through object properties.

Syntax

for(property in object) {
    //executable code
}

Executable code executes once for each property of an object.

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}

var car = new Vehicle('Audi', 'A4', '2009', 'Red');

carInfo = '';
for(var prop in car) {
    carInfo += 'Car '+prop+' : '+car[prop]+'<br />';
}

document.getElementById('text').innerHTML = carInfo;
</script>

</body>
</html>

Download the code Run the code

Add new Properties

You can add new property to an existing object by passing property value.

<!DOCTYPE html>
<html>
<body>

You can add a new property to an exising object.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
}

var car = new Vehicle('Audi', 'A4', '2009', 'Red');
car.color = 'Red';
document.getElementById('text').innerHTML = 'Car color is '+car.color;
</script>

</body>
</html>

Download the code Run the code

Delete property

Delete keyword is use to delete any property from an object.

<!DOCTYPE html>
<html>
<body>

The delete keyword is used to remove property.
<p id="text"></p>

<script>
var car = {make:"Audi", model:"A4", mfgYear:"2007"}

delete car.mfgYear
document.getElementById('text').innerHTML = 'Car is manufactured in year '+car.mfgYear;
</script>

</body>
</html>

Download the code Run the code

The delete keyword deletes object property and its value both. Deleted property cannot be used until it is assign again.

The delete keyword should not be use with JavaScript built-in properties. Using it with built-in properties can result in crash an application.

Property attributes

All object properties have a name as well as value.

The property value is an attribute of a property.

In JavaScript, all the attributes are read only, but value attribute can be change.

Prototype Properties

In JavaScript, all objects inherits the properties of their prototype.

The delete keyword does not delete properties inherited from its prototype.

JavaScript Object Prototypes

In previous chapter we learn about object methods. In this chapter we will learn about Object Prototypes

Object Prototypes

Every JavaScript Object has a prototype which is also an object. Prototype is like a parent object.

All JavaScript objects i.e Date, Array, RegExp, Function, etc.. inherit from the parent prototype Object.prototype.

Every JavaScript Object inherits properties and methods of its prototype object.

JavaScript Prototypes

JavaScript Prototype is a top most parent of all objects.All JavaScript objects inherits the properties and methods from prototype.

Objects create by an object literal method, or with new Object(), inherit parent prototype Object.prototype.

Objects create using new Date(), inherit parent prototype Date.prototype

Create Prototype

You can create an object prototype using an object constructor method as shown below.

function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}

This is a standard method of create an object prototype. Once constructor function is define, you
can use the new keyword to create new objects from same prototype.

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
var van = new Vehicle('Toyota', 'Auris', '1997', 'White');

document.getElementById('text').innerHTML = 'Color of car is '+car.color+'. Color of van is '+van.color;
</script>

</body>
</html>

Download the code Run the code

Add a Property to an Object

It is very easy to add a new property to an existing object.

<!DOCTYPE html>
<html>
<body>
Car weight is defined after an object is created.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
car.weight= '1000kg';

document.getElementById('text').innerHTML = 'Weight of a car is '+car.weight;
</script>

</body>
</html>

Download the code Run the code

The new property weight will be added to car only and not to van or any other vehicle object.

Add new method to an Object

It is also easy to add a new method to an existing object.

<!DOCTYPE html>
<html>
<body>
Car manufacturer method is defined after an object is created.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
	
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
car.manufacturer = function() {
    return this.make+' '+this.model;
};

document.getElementById('text').innerHTML = 'Car manufacturer is '+car.manufacturer();
</script>

</body>
</html>

Download the code Run the code

Same like new property, this new method will be added to car and not with any other vehicle object.

Add propertes to Prototype

Adding a new property to prototype is not same as adding a property to an existing object, because prototype is not an existing object.

To add a new property to prototype, you must add it to object constructor function.

<!DOCTYPE html>
<html>
<body>
It is not possible to assign a new property to a new prototype constructor function.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
    this.sub_type = "Sedan";
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
document.getElementById('text').innerHTML = 'Car type is '+car.sub_type;
</script>

</body>
</html>

Download the code Run the code

Add methods to Prototype

You can also add methods to constructor function.

<!DOCTYPE html>
<html>
<body>
You can add new method to prototype constructor function.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
    this.manufacturer = function() {
		return this.make+' '+this.model;
	};
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
document.getElementById('text').innerHTML = 'Car manufacturer is '+car.manufacturer();
</script>

</body>
</html>

Download the code Run the code

Using prototype property

The prototype property of JavaScript allows you to add properties and methods to existing prototype.

Example

<!DOCTYPE html>
<html>
<body>
You can add new method to prototype constructor function.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}

Vehicle.prototype.sub_type = "Sedan";

var car = new Vehicle('Audi', 'A4', '2009', 'Red');
document.getElementById('text').innerHTML = 'Car subtype is '+car.sub_type;
</script>

</body>
</html>

Download the code Run the code

<!DOCTYPE html>
<html>
<body>
You can add new method to prototype constructor function.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}
		
Vehicle.prototype.manufacturer = function() {return this.make+' '+this.model;};

var car = new Vehicle('Audi', 'A4', '2009', 'Red');
document.getElementById('text').innerHTML = 'Car manufacturer is '+car.manufacturer();
</script>

</body>
</html>

Download the code Run the code

JavaScript Objects Definition

JavaScript Object Definition

JavaScript Object Definition- In JavaScript, everything is basically an Objects.

  • Booleans can be objects
  • Numbers can be objects
  • Strings can be objects
  • Dates are always objects
  • Maths are always objects
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are objects

All values except primitive values are objects.

Examples of primitive values are: strings(“XYZ”), numbers (1,2,3), true, false, null and undefined.

Objects are Variables

A JavaScript variable can contain only one value.

 var redfruit = "Apple"; 

Objects are also variables, but an object can contains many values.

An object can be written as a name:value pair, separate by colon(:)

Example

<!DOCTYPE html>
<html>
<body>

<p>Create an object</p>


<p id="text"></p>

<script>
	var category= {
			type:"Clothes", 
			cat:"Women cloths", 
			sub_cat:"Winter wear", 
			getCategoryName:function() {return this.cat;}
		};
		
	document.getElementById('text').innerHTML = category.getCategoryName();
</script>

</body>
</html>

Download the code Run the code

Objects Properties

Name value of an object is object properties.

In above object “category”, the name values i.e. type, cat and sub_cat are object properties.

Object Methods

Object Methods are an actions that can be perform by an Object. An object method is a property having a function definition.

In above example, category object getCategoryName is an object method.

In next chapters, you will learn more about object properties and object methods.

Creating a JavaScript Object

There are many ways to create a JavaScript Object.

  • Define and Create object using an object literal
  • Define and Create object using new keyword
  • Create object using object constructor

Create object using an object literal

This is a very simple way to create a JavaScript Object. Using this method you can define and create object in single statement.

Example

<!DOCTYPE html>
<html>
<body>

<p>Create an object</p>


<p id="text"></p>

<script>
	var category= {type:"Clothes", cat:"Women cloths", sub_cat:"Winter wear", getCategoryName:function() {return this.cat;}};
		
	document.getElementById('text').innerHTML = "This category is for "+ category.sub_cat;
</script>

</body>
</html>

Download the code Run the code

Space, tabs and new lines are not important. An object definition can be on multiple lines.

<!DOCTYPE html>
<html>
<body>

<p>Create an object</p>


<p id="text"></p>

<script>
	var category= {
		type:"Clothes", 
		cat:"Women cloths", 
		sub_cat:"Winter wear"
	};
		
	document.getElementById('text').innerHTML = "This category is for "+ category.sub_cat;
</script>

</body>
</html>

Download the code Run the code

Define and Create object using new keyword

You can create a new object using a new keyword as shown in below example.

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>
var category= new Object();
category.type = "Clothes";
category.cat:"Women cloths";
category.sub_cat:"Winter wear";
		
document.getElementById('text').innerHTML = "This category is for "+ category.sub_cat;
</script>

</body>
</html>

Download the code Run the code

Both above examples do same things, hence it is good to use first notation.

Create object using object constructor

There are few limitations with create an object using above methods. You can create only one object using it.

There is possibility two have more than one object with same type.

Example

In the below code, Vehicle is object constructor. Once you have a object constructor, you can create a new object from it using new keyword same way as you have seen above.

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>
<p id="text1"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
var van = new Vehicle('Toyota', 'Auris', '1997', 'White');

document.getElementById('text').innerHTML = "Car make & model : "+ car.make + ' ' + car.model;
document.getElementById('text1').innerHTML = "Van make & model : "+ van.make + ' ' + van.model;
</script>

</body>
</html>

Download the code Run the code

this keyword

this is an object which refers current object or own object.

So when this is used within function, this refers to current function .

When this is used within object, this refers to current object itself.

this is not a variable, so it is not possible to change its value or assign value.

Built-in Constructors

There are many built-in JavaScript constructors.

<!DOCTYPE html>
<html>
<body>

<p id="text"></p>

<script>

var x1 = new Object();    
var x2 = new String();    
var x3 = new Number();    
var x4 = new Boolean();   
var x5 = new Array();     
var x6 = new RegExp();    
var x7 = new Function();  
var x8 = new Date();     
		
document.getElementById("text").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";

</script>

</body>
</html>

Download the code Run the code

Mutable objects

Objects are addressed by reference , and not by value. If car is an object, below statement will not create a copy of person.

<!DOCTYPE html>
<html>
<body>

JavaScript objects addresses by reference. Changes to copy of an object applies to original object as well.
<p id="text"></p>

<script>
function Vehicle(make, model, mfgyear, color) {
    this.make = make;
    this.model = model;
    this.mfg_year = mfgyear;
    this.color = color;
}
		
var car = new Vehicle('Audi', 'A4', '2009', 'Red');
var newcar = car;
newcar.color = "White";

document.getElementById('text').innerHTML = "Car color is "+ car.color;
</script>

</body>
</html>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .