On Tue, Feb 15, 2011 at 10:17 AM, Ivan S <ivan.sku...@gmail.com> 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/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com