Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: Passing an Object by Reference
07-29-2008, 10:59 PM #1
- Join Date
- Jul 2008
- Thanked 0 Times in 0 Posts
Passing an Object by Reference
I noticed the other day that I do not have to pass an Array to a Function in order for that Function to access the content of the Array.
From what I have learnt (and its not very much so far!) if you wish to use a value that exists outside a Function within that Function then you need to pass that value into the Function, either by value or by reference, as follows;
var x = 1;
a += a;
The above example is obviously passing by value, but you would think the same 'rules' would apply to an object such as an Array; it has to be passed to the Function before you can use its contents.
I was messing with some scripts that involved two separate Functions and I wanted to pass an Array between the two. I could not call one Function from the other as both were unrelated and were triggered by separate events. To do this I declared the Array outside of both Functions and then referred to the Array within the Functions without passing by reference, or at least without placing a variable within the brackets of my Function. And it worked! Example;
var x = new Array();
Any idea why I did not have to pass the Array into the function at all? Clearly my second example shows this works, but my main concern is that it is not the "correct" way of doing it. This seems to contradict what I have been learning.
Thanks for your time.
07-30-2008, 11:13 AM #2
- Join Date
- Jun 2007
- Thanked 567 Times in 548 Posts
if the variable is in the scope outside the two functions, either global or in that of a parent function, the variable can be referred to but all subsequent lower scopes.
you examples create a global, which can be reached anywhere.
arrays are objects, and like all objects are passed by references. primitives are asses at time of calling and are thus passed as values.