-1

I have a question about referencing objects in javascript.

Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).

If I go ahead and declare

var objTwo = objOne;

will I have two references to the same Object? Kind of like a c pointer?

Tim Ashton
  • 436
  • 6
  • 18

2 Answers2

0

To sum it up :

  • assignements are done by value
  • you never manipulate objects, only object references

This means that

  • you'll have two references to the same object (you can check that by changing a property of the object)
  • when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables

EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Yes, objects are passed by reference:

function changeVal(obj){
    obj.value = "bar"
}

(function checkRefs(){

    var myObject = {
        value: "foo"
    };


    alert(myObject.value);

    changeVal(myObject);

    alert(myObject.value);


})();
Sheldon Neilson
  • 803
  • 4
  • 8