Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

appending to objects

Status
Not open for further replies.

mjpearson

Technical User
Dec 13, 2002
196
US
I'm relatively new to JS. I read somewhere that I can do the following:

function stuff ( item ) {
this.valuable = item;
}

my_junk = new stuff( "teddy bear" );

function containers( container_item ) {
this.container = container_item;
}

my_container = new containers( "house", my_junk );

document.write( my_container.my_junk.valuable );

**********************
But I can't get it to work, however, I've seen it done this way [and I can get this to work]:
**********************
my_container = new containers( "house" );
my_container.my_junk = my_junk;

document.write( my_container.my_junk.valuable );

**********************
Did mis-read something? I'd prefer to use the first syntax to make life easier. What am I doing wrong?


mike
 
The first syntax you use has a flaw in it - you're passing two arguments to the constructor of "containers", and yet you're only receiving 1 argument into the constructor. Perhaps this is why you're not expecting the results you want?

You're also writing out a property of your "container" called "my_junk", which does not exist (you've never defined a property called "my_junk" in the context of "my_container".

Try something like this:

Code:
function stuff(item) {
	this.valuable = item;
}

my_junk = new stuff('teddy bear');

function containers(container_name, container_item) {
	this.name = container_name;
	this.item = container_item;
}

my_container = new containers('house', my_junk);

document.write('Inside the container named: ' + my_container.name + ' there is an item: ' + my_container.item.valuable);

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Also, read up on "prototype" (not to be confused with the Prototype JS framework) and OO JS techniques:






Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Thanks,

I've been busy but meaning to write back. I went to some of the references that you provided and several were well over my head but I hope to revisit them soon and really sit down and study them in depth.

Yes, I came to the same conclusion about passing arguements thus my original question. I suspect the book I was referencing was wrong or incomplete.

I used your technique and it worked.

Thanks again,


mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top