create objects in JavaScript

Giganews Newsgroups
Subject: create objects in JavaScript
Posted by:  androids…@yahoo.com (js)
Date: 31 Jul 2003

Two questions:

1. I created Javascript objects called oNewObj using {} construct as
in the follwoing code segment. When I clicked on the <td> element, I
got runtime error "oNewObj is undefined".  When I changed the <td>
onclick event to doThis(this), then I can exam (this) object.
However, I really want to exam the oNewObj.  Does anyone know how to
do it?  Thanks.

2. I need to add additional things to the oNewObj, how could I append
new object to it so that it would look like: {things:[{code:100,
color:'green'}],[{key:215, color:'red'}]};

<html>
<body>
<script language='javascript'>
<!--
var oNewObj = {things:[{code:1, color:'abc'}]};
var strHTML;

strHTML = "<table><tr>"
strHTML += "<td id='1' onclick='javascript:doThis(oNewObj)'>click
this</td>"
strHTML += "</tr>"
strHTML += "<tr>"
strHTML += "<td id='2' onclick='javascript:doAll(oNewObj)'></td>"
strHTML += "</tr></table>"
DIVresult.innerHTML = strHTML;

function doThis(o)
{
  alert(o.things[this.id].code + '
' + o.things[this.id].color);
}

function doAll()
{
  var i;
  for (i=0; i<=oNewObj.things.length; i++)
    alert(oNewObj.things[i].code + '
' + oNewObj.things[i].color);
}
//-->
<DIV id='DIVresult'></DIV>
</body>
</html>

Replies