Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Javascript variable not have an object pass by reference?

Tags:

javascript

I'm passing an object into a function. I'm pulling out a property of the object which is a sub object for easy reading. However, that second object does not effect it's analogous property on the first object. Why is this?

I want the processItem.event outside of the function scope to be updated when the event is saved. Why do have to update processItem and not just the local variable which points to it?

This works:

this.submitForm = function(processItem) {
    var event = processItem.event
    if (event.new) {
        EventDataService.create(event).then(function(response) {
            processItem.event = response.data;
        });
    } else {
        EventDataService.update(event).then(function(response) {
            processitem.event = response.data
        });
    }
};

and this doesn't

this.submitForm = function(processItem) {
    var event = processItem.event
    if (event.new) {
        EventDataService.create(event).then(function(response) {
            event = response.data;
        });
    } else {
        EventDataService.update(event).then(function(response) {
            event = response.data
        });
    }
};
like image 813
Adam S Avatar asked Mar 15 '23 05:03

Adam S


1 Answers

var event = processItem.event

Now event refers to the same thing as processItem.event

event = response.data

Now event refers to the same thing as response.data, and does not refer to the same thing as processItem.event any more. It is very different from

processItem.event = response.data

which would make processItem.event co-refer with response.data (but not with event any more).

This has nothing to do with function arguments, but with the fact that JavaScript has references, and not aliases.

like image 176
Amadan Avatar answered Apr 19 '23 23:04

Amadan