Objects are a big thing in programming. They are essential in an object oriented programming (OOP) and they are built to abstract from long lines of procedural code.
JavaScript supports the concept of objects.
Defining an object
The first way of defining an object is the clearest and easiest to understand and follows a syntax similar to other languages.
Using the new Object()
keyword combination is similar
to other languages:
var pet = new Object();
The next step is to give the object some values:
//Pet object var gismo = new Object(); gismo.name = "Gismo"; gismo.type = "Cat"; gismo.dob = "10/03/1998"; var petro = new Object(); petro.name = "Petro"; petro.type = "Rabbit"; petro.dob = "29/04/2007";
These values within the objects can then be accessed using the same method as setting the values:
//Pet object var petro = new Object(); petro.dob = "29/04/2007"; alert(petro.dob);
Using the object initialiser
The previous method of creating objects is just one way of doing this. An alternative is to use the object initialiser syntax, which is similar to the C++ method of creating objects.
The previous pet example could be simplified to:
//Pet object var gismo = { name : "Gismo", type : "Cat", dob : "10/03/1998" }; //Pet object var petro = { name : "Petro", type : "Rabbit", dob : "29/04/2007" };
Using the object initialiser can also be used to create arrays.
Inner values (properties) can still be accessed the same way:
//Pet object var petro = { name : "Petro", type : "Rabbit", dob : "29/04/2007" }; alert(petro.dob);
Creating with a constructor
The third method of creating an object in JavaScript is with a constructor function. A constructor is a method that is normally called when the object is created.
The this
keyword refers to the object that the code is executed within.
JavaScript differs from many languages in that the function becomes the context for the
this
keyword. This allows code to execute in a function like an object:
//Pet object function Pet(name, type, dob){ this.name = name; this.type = type; this.dob = dob; return this; } var petro = new Pet("Petro", "Rabbit", "29/04/2007"); alert(petro.dob);
That's all there is to objects. JavaScript objects can be used to mimic real world objects just as shown above.