The object types are very important part of JavaScript as they allow programmers fully engaging in OOP (object oriented programming). Properly applying OOP enables creation of larger, fast executing scripts that make JavaScript so popular in web development.
The objects essentially are collections of properties and methods.
Properties are basically variables attached to objects and they are expressed in name-value pair.
Methods are functions associated with objects, i.e. they need an existing object to be applied to. Methods may be also explained as actions performed on an object by using or affecting object's properties.
Example
Definition: Person is an object. He (or she) can have a name, age, gender, job… to define him. These are called properties. They can vary from person to person. He can do actions like going to work, getting pension, going on holiday … These actions are called methods and are performed at different times.
var person = {
name : "Kathy", //Properties …
age: 32,
gender: "female",
getPension : function() { //Method
if(this.age < 60) {
document.write("Not eligible for pension");
}
}
};
Creating and invoking Objects
Objects can be created in a few ways; the most common being object initialization and object constructor.
Objects are invoked using ‘.’ (dot operator) or ‘[ ]’ ([ ] operator).
Object initialization
How to initialize objects in JavaScript:
var obj = {property1: value1, property2:value2, ….. property:valueN};
where obj is name of a new property,
property1,2…..N are identifiers i.e. string, number, name…etc.
value1,2……N are values of particular property.
Example of object initialization:
var Kate = {name : "Kathy", age: 32, gender: "female"};
var Chris = {name : "Christopher", age: 29, gender: "male"};
document.write(Kate.name);//Accessing using ‘.’ Operator
document.write(Kate[“name”]); //Accessing using ‘[]’ Operator
Each of the above expressions result in creating a new objects when executed with distant properties.
Constructor function
We define an object type by writing a constructor function (whose name is in capital initial letter) and create an instance of the object using keyword new. The constructor function is a "blueprint" of the type of objects we define.
The object Constructor function in JavaScript is created like this:
function Film(name, year, director){
this.name = name;
this.year = year;
this.director = director;
this.display = function() {
document.write(this["name"] + " is released in " + this["year"] + " directed by " + this["director"]);
};
}
var hobbit = new Film("Hobbit 3", 2014, "Peter Jackson"); //Creating object using constructor.
hobbit.display();
Example
Example of JavaScript object used to define a person:
Comments
No comments have been made yet.
Please login to leave a comment. Login now