Locally var.s affect global ones

A

Andrew Poulos

Say I have script that looks a bit like this:


Array.prototype.getValue = function(ind, dir) {
if (dir !=0) ind[ind.length-1] += dir;
// more script
}

screens = [...// a big array
fnd = [1,2,3];
// 1.
a = findStart(fnd);
// 2.
b = findEnd(fnd);

findStart = function(cs) {
return screens.getValue(cs, 1);
}

findEnd = function(cs) {
return screens.getValue(cs, -1)
}


As I go from 1. to 2. the value of fnd changes. I don't understand how a
locally scoped variable might be affecting a global one.

Andrew Poulos
 
M

Martin Honnen

Andrew said:
fnd = [1,2,3];
// 1.
a = findStart(fnd);
// 2.
b = findEnd(fnd);

As I go from 1. to 2. the value of fnd changes. I don't understand how a
locally scoped variable might be affecting a global one.

What you have above is a variable fnd which contains a reference to an
array object and whereever you pass fnd to you pass in the reference to
that array object and any function then operates on the array object fnd
references.
So it is not suprising in JavaScript that an object or array object is
manipulated if you pass it to a function or method, no copies of objects
respectively array objects are created, instead references to objects
are passed around. Pretty much the same as in Java where you have value
types and reference types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top