Home > Javascript > Object Manipulation in Javascript

Object Manipulation in Javascript

Object manipulation in JavaScript refers to accessing the objects properties and methods at runtime to perform certain functionality. JavaScript uses “for…in” and “With” statements to manipulate objects.

  • for…in Statement

The for…in statement iterates a specified object for all the properties. For every properties the object has JavaScript executes the series of statements specified by the user.

Syntax:

for (variable in object)
{
  statements
}

Example:

<script type="text/javascript">
   var x;
   var employee = new Object();
   employee.name = "John";
   employee.designation = "Software Engineer";
   employee.gender = "Male";
   for (x in employee)
   {
      document.write(x + "---" + employee[x] + "<br />");
   }
</script>

Output
name—John
designation—Software Engineer
gender—Male

Example Explanation:
Here i am creating an custom object “employee”. It has 3 properties name, designation and gender. Now i am looping to the employee object and all the details of employee object gets stored in variable x. Now here it creates an Associative Array of the Properties and its values. To know more on Associative Array check out Associative Array in JavaScript.

  • With Statement:

The with statementt allows you to iterates to the default object for a set of statements.

Syntax:

with (object)
{
  statements
}

Example:

<script type="text/javascript">
   var a, x, y;
   var r=10
   with (Math)
   {
      a = PI * r * r;
      x = r * cos(PI);
      y = r * sin(PI/2);
   }
</script>

Your email:

 

Explanation of the Example
Here i am loading the Math Object of JavaScript inside the With Statement. So now if i want to access the methods of the Math Object i can now directly access it with typing the method name.


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Javascript Tags:
  1. No comments yet.
  1. No trackbacks yet.