Objects in Javascript

Almost “everything” is an object in JavaScript.

Strings, Numbers, true, false, null and undefined all are primitive values in JavaScript. Others are objects.

Dates, Maths, Regular expressions, Arrays, Functions and Objects are objects in JavaScript.

Strings, Numbers and Booleans can be objects.

In JavaScript, Variable can contain single value but Object can contain many values. And Object is also variable.

var Person = “Vikas Jindal”;

var Person = { firstName : “Vikas”, lastName : “Jindal”, Occupation : “Software Developer”, webSite : “www.vikasjindal.com” };

The values are written as name : value pairs in object.

What is named values?

An object is an unordered collection of variables called named values in JavaScript.

In JS’s object, name of values or variables are called properties.

Example of properties: firstName, lastName, Occupation, website.

How to create object in JavaScript?

Object Creation

3 ways to create new objects:

  1. Object Literal – Define and create a single object.
  2. With new keywords – Define and create a single object.
  3. Using an Object constructor.

1) Object Literal – An easiest way to create an object. You define and create an object in one statement.

var Person = { firstName : “Vikas”, lastName : “Jindal”, Occupation : “Software Developer”, webSite : “www.vikasjindal.com” };

2) With new keyword –

var Person = new Object();

Person.firstName = “Vikas”;

Person.lastName = “Jindal”;

Person.Occupation = “Software Developer”;

Person.webSite = “www.vikasjindal.com”;

3) Using an Object constructor – can create many objects.

function Person(fName, lName, occupation, website) {

        this.firstName = fName;

        this.lastName = lName;

        this.Occupation = occupation;

        this.webSite = website;

}

var developer = new Person(“Vikas”, “Jindal”, “Project Leader”, “www.vikasjindal.com”);

var astrologer = new Person(“VJ”, “Baba”, “Astrologer”, “www.theastroganesha.com”);

Vikas Jindal

vikkasjindal@gmil.com

www.vikasjindal.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s