OK, thanks.


On Tuesday, February 15, 2011 10:41:37 AM UTC+1, Peter van der Zee wrote:
>
> On Tue, Feb 15, 2011 at 10:17 AM, Ivan S <[email protected]> wrote:
>
>> Let's say we have this example:
>>
>
> (There's no need for the html cruft..)
>  
>
>> function testPassByRef() {
>>     var obj = {};
>>     
>>     (function(passed_obj) {
>>         passed_obj = {prop : 'test'}
>>         window.alert(passed_obj.prop);
>>     }(obj));
>>     
>>     window.alert(obj.prop);
>> }
>>
>>
> Functions have local variables. Not counting getters and setters, assigning 
> to a variable only changes the value for that variable and therefore have no 
> effect on the previous value of that variable (the object).
>  
>
>> The result is:
>>
>> test
>> undefined
>>
>
> Because in the inner function you're assigning something to a local 
> variable. The outer variable is not affected.
>  
>
>> So, I can see intuitively that in JavaScript objects are not passed by 
>> reference. Actually, I think object reference is copied (or new one is 
>> created, whatever), something like this:
>>
>
> No, objects are passed by reference which means you can change properties 
> of that object and these changes are reflected through any variable that 
> holds that object. You're expecting variables to be passed by reference like 
> a pointer. That magic doesn't happen in js.
>  
>
>> Is this explanation good one?
>>
>
> It was confusing to me. I hope my answers help you.
>
> Also, I was wondering how I can change that original reference (actually, 
>> variable containing reference) references to the newly created object? I 
>> suppose returning reference to the newly created object and assigning it to 
>> the original reference/variable is the only way, but is there another way?
>>
>
> JS has the concept of closures. Outer variables are accessible (read/write) 
> from inner scopes. So in your example, you could have just assigned to `obj` 
> in the inner anonymous function. That would have changed the value of obj 
> and have your desired effect of two times alerting "test".
>
> Some examples:
>
> // pass by reference
> var x = {y:5};
> (function(z){
>     z.y = 6;
>     alert(z.y);
>     alert(x.y);
> })(x);
> alert(x.y);
> // 6, 6, 6
>
> // closure
> var x = {y:5};
> (function(z){
>     x = {y:10};
>     alert(x.y);
> })(x);
> alert(x.y);
> // 10, 10
>
> // local variables
> var x = {y:5};
> (function(z){
>     z = {y:10};
>     alert(z.y);
>     alert(x.y);
> })(x);
> alert(x.y);
> // 10, 5, 5
>
>
> - peter
>

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to