JS Objects

Ojects are variable too but it contains many values. The values are written as name : value pairs.

Object Literal Method
This method is the easiest way to create Javascript object. Below is the example of creating oject with three properties.

var person = {
 firstName : "Bill",
 lastName : "Gates",
 age : 30
}
alert(person.firstName + " is " + person.age + " years old.");
OR alert(person["firstName"] + " is " + person["age"] + " years old.");

Object Constructor
function person(first, last, age) {
 this.firstName = first;
 this.lastName = last;
 this.age = age;
}
var prBill = new person("Bill", "Gates", 30);
var prSteve = new person("Steve", "Jobs", 32);
alert(prBill.firstName + " and " + prSteve.firstName + " are " + prBill.age + " and " + prSteve.age + " years old.");

Share this

Related Posts