PDA

View Full Version : Variable Declaration and References


Guardian23
09-17-2002, 07:42 AM
Ok, quick review before I pop the question:

//for a variable you declare as such
var myVAR = varvalue
//for a reference to a path in the DOM you declare as such
mypath = document.pathpart1.pathpart2//and so on

But if you do this:

var x = 2
var y = x
//and then do this
x = 3
alert (y) //it returns 2!

Where as in PerlScript

my $x = 2;
my $y = \$x;
$x = 3;
$window-> alert ($y) #it returns 3!

So in JavaScript:
 (1) how can you successfully create a reference to a
variable,
&
 (2) how can you successfully copy the contents of
DOM childNode to a variable?

Guardian

joh6nn
09-17-2002, 08:13 AM
objects are passed by reference in javascript. if your variable isn't an object, you can't reference. because it is later, and i am tired and hungry, i will offer you this horrible horrible, not worth using at all, hack, on how to create a single variable that you may reference.

var x = [2];
var y = x;
x[0] = 3;
alert(y); // alerts 3.

var x = [2];
var y = x;
y[0] = 3;
alert(x); // alerts 3.

this works because an array is an object, and is passed by reference. note that i didn't try to change x or y, i changed x[0] and y[0]. yes, it is a really bad hack.

copying a node is easy. there's method that does it for you.

var somevar = document.pathname1.pathname2.node.cloneNode(boolean);

where boolean is true if you want to clone all of it's children, too, and false, if you don't.

good night, y'all.

Guardian23
09-17-2002, 08:41 AM
 Well, even if the hack was horrible (I'll just take your word on that
part), at least I now have a better understanding of data types
in JS.

Thanks joh6nn, but if I put in false for the boolean variable, what
does that leave me with?
*looks down at empty hands*
:confused:
Guardian,

PS. For a horrible hack, at least you (generally speaking) could
declare the variable as an array and create a function that would
pass in the values of each array in question (although I must admit,
I've never been able to make them work together very well: my
arrays come back to me empty!)

adios
09-17-2002, 06:00 PM
No pointers in JS; as joh6nn noted, objects give you some control over variable assignments - with primitives, a copy is simply created and stored (as the Wrox JS book observes 'twos are cheap'...). A little less sucky (IMO):

<script type="text/javascript" language="javascript">

var x = {val:2}
var y = x;
//and then do this
x.val = 3
alert (y.val) //it returns 3!

</script>