HTML Dog
Skip to navigation

Objects

JavaScript objects are like a real life objects; they have properties and abilities. A JavaScript object is, in that sense, a collection of named properties and methods - a function. An object can be stored in a variable, and the properties and methods accessed using the dot syntax.

A human, for example, has a name and an age, and could talk, move or learn JavaScript. Name and age are properties of the human, and are essentially pieces of data. Talking, moving and learning are more like functions - there’s some complex behavior involved. When a JavaScript object has such an ability, it is called a method.

Variables can hold objects, and creating an object is done using a special syntax signified by braces:


var jedi = {
    name: "Yoda",
    age: 899,
    talk: function () { alert("another... Sky... walk..."); }
};

The Jedi’s name and age are properties - they are essentially variables within the object and can store anything a variable can. talk is a property that holds a function - a method.

You can get data back out of an object using the dot syntax:


jedi.name;

Yoda

jedi.age;

899

jedi.talk();

//produces an alert box

You can also reassign properties of an object:


jedi.name = "Mace Windu";

And add new ones on the fly:


jedi.lightsaber = "purple";

Properties can be any kind of data including objects and arrays. Adding an object as a property of another object creates a nested object:


var person = {
    age: 122
};

person.name = {
    first: "Jeanne",
    last: "Calment"
};

Creating an empty object and adding properties and methods to it is possible too:


var dog = {};

dog.bark = function () { alert("Woof!"); };