dcsimg
www.webdeveloper.com
Results 1 to 2 of 2

Thread: Passing Arguments (reference vs value)

  1. #1
    Join Date
    Sep 2015
    Posts
    63

    Passing Arguments (reference vs value)

    from the book "Professional Javascript for Web Developers 3rd edition" :

    I am trying to understand a concept about arguments passing (reference vs value). This might be a simple concept, but I have been reading again and again the same pages, only to feel frustrated.

    -------------

    "All function arguments in ECMAScript are passed by value. This means that the value outside of the function is copied into an argument on the inside of the function the same way a value is copied from one variable to another. If the value is primitive, then it acts just like a primitive variable copy, and if the value is a reference, it acts just like a reference variable copy. This is often a point of confusion for developers, because variables are accessed both by value and by reference, but arguments are passed only by value."


    Example 1:

    function setName(obj) {
    obj.name = “Nicholas”;
    }
    var person = new Object();
    setName(person);
    alert(person.name); //”Nicholas”


    "Many developers incorrectly assume that when a local change to an object is reflected globally, that means an argument was passed by reference.To prove that objects are passed by value, consider the following modified code:"


    Example 2 :

    function setName(obj) {
    obj.name = “Nicholas”;
    obj = new Object();
    obj.name = “Greg”;
    }
    var person = new Object();
    setName(person);
    alert(person.name); //”Nicholas”


    -------------

    Why Example 1 reflects "Nicholas" outside the function, but Example 2 does not reflect "Greg" ?


    Thanks in advance!
    Bruno.

  2. #2
    Join Date
    Mar 2011
    Posts
    114
    I hope what I've written is clear enough. In javascript the reference to an object is considered a value, therfore you can change the properties of that object by obj.name = "Nicholas";. So the argument 'obj' is a reference to the 'person' object. Because the reference is considered a value, when you come to the line 'obj = new Object();', obj gets a new value (an empty object) but the 'person' object is unaffected. When you then come to obj.name = "Greg"; it affects the new empty object.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles