Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2008
    Posts
    4
    Thanks
    0
    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;

    Function myfunction(a)
    a += a;

    document.write(myfunction(x));

    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();

    Function one()
    do.stuff.using.array();

    Function two()
    do.other.stuff.with.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.

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,379
    Thanks
    11
    Thanked 592 Times in 572 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.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •