JavaScript Objects

Everything in JavaScript is an Object. Even primitype datatypes (except null and undefined) can be treated as objects.

Accessing JavaScript Objects

  • Accessing Object Properties

Syntax :  objectName.propertyName

Example:

var strLen=”string is here”;

var x= strLen.length;    // OUTPUT: 14

  • Accessing Objects Methods

Syntax:  objectName.methodName()

Example:

 var message=”convert this into uppercase”;

var x=message.toUpperCase();   // output: CONVERT THIS INTO UPPERCASE

Creating JavaScript Objects

  • Creating a Direct Instance

friendsDetails=new Object();

friendsDetails.firstname=”John”;

friendsDetails.lastname=”Abrahm”;

another way to create direct instance of object as bellow:

 friendsDetails={ firstname=”John”, lastname=”Abrahm”};

  • Using an Object Constructor

function person(firstname,lastname)
{
this.firstname=firstname;
this.lastname=lastname;
}

Adding Methods to JavaScript Objects

function person(firstname,lastname)
{
    this.firstname=firstname;
    this.lastname=lastname;
     
    this.changeName=changeName;
    function changeName(name)
    {
      this.lastname=name;
    }
}
The changeName() function assigns the value of name to the person's lastname property.
myMother.changeName("Pole");  // this will change the last name to Pole

 

Object properties with for..in loop

var person={fname:”John”,lname:”Doe”};
for (x in person)
{
txt=txt + person[x];
}

Leave a Reply