/

HTML / CSS / JavaScript Tutorial

JavaScript Tutorial: Objects

[this page | pdf | back links]

JavaScript is an object-orientated programming language (like most other more sophisticated general-purpose computer languages) and technically almost all of its components are objects of some sort or other.

 

JavaScript objects are containers that contain properties and methods. For example, a statement such as:

 

var person = {title:"Mr", surname:"Smith", age:30}

 

creates an object that has three properties, i.e. name-value, pairs that in this instance characterise (some of the features of) a person.

 

Object properties can be accessed in two ways, either here e.g. person.title or person["title"] (both of which in this instance would return a value of "Mr"). An array is a specific type of object with the property names indexed from 0 up to the length of the array less 1 (and hence elements of arrays can themselves be arrays (or other sorts of objects).

 

Object methods are technically also property-like in nature, i.e. again come in name-value pairs, but with the ‘name’ being a function name and the ‘value’ being a JavaScript function. For example,

 

<!DOCTYPE html>

<html><head><title>JavaScript Objects</title></head>

<body>

<p>An example of a  JavaScript object</p>

Full Name: <span id="Added"></span><br><br>

Contrast evaluating the function with the contents of the corresponding property which is:<br>

<span id="Added2"></span>

<script>

window.addEventListener('load', addtext());

function addtext() {

var person = {

   firstName: "John",

   lastName: "Smith",

   fullName: function()

      {return this.firstName + " " + this.lastName}

   }

document.getElementById("Added").innerHTML=person.fullName();

document.getElementById("Added2").innerHTML=person.fullName;

}

</script>

</body>

</html>

 

creates an object with a method called fullName. The method is evaluated by calling it as a function (in this case it has no parameters so this involves e.g. person.fullName()). In contrast the property fullName (accessed by person.fullName, without the ending bracket pair) is the function itself, rather than what the function evaluates to.

 

Objects have some generic properties, including their constructor, length and prototype properties.

 


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Objects


Desktop view | Switch to Mobile