Friday, June 13, 2008

Concept of reference in javascript

The basic concept of reference in javascript is the pointer to the actual location of an object. let take a look at the example and see how reference react in object assignment.

// Set items to an array (object) of strings
var items = new Array( "one", "two", "three" );

// Set itemsRef to a reference to items
var itemsRef = items;

for(el in itemsRef) alert(itemsRef[el])

The output will be "one", "two", "three".

Let add some more element to an array through push() method

items.push("four");
items.push("five");
for(el in itemsRef) alert(itemsRef[el])

The output will "one", "two", "three", "four", "five"

The itmesRef has a reference to items, thus anychange to items will also change in itemsRef

No comments: