1

I'm having some troubles to understand what is copied and what is referenced in javascript. What is clear to me is that an object is referenced when it's an object and copied when it's a variable:

var reference = myObject    // myObject = {string:'text'} -> referenced
var copy = myVar            // myVar = 'text' -> copied

Now what if I want to create an object of objects/var?

var newObject = {anObject: myObject, aVar: myVar}

Will they be copied or referenced? If they are copied, is there a way to make them referenced (at least the object: myObject)?

Edit (Angularjs specific): I wanted to make sure that everything answered is also true with AngularJS and the $rootScope variables (even though I guess the behavior should be identical)

Nate
  • 7,606
  • 23
  • 72
  • 124

2 Answers2

1

Objects are Passed by Reference In JavaScript

object references are values. Because of this, objects will behave like they are passed by reference: If a function changes an object property, it changes the original value. Changes to object properties are visible (reflected) outside the function.

if you assign an object to property of another object it is still assigned by reference. while you change the new object value it reflect in base.

eg:

var myObj = {
  a: 1
}

var testObj = {
   ref: myObj
}

console.log(myObj.a); //1

//change the value from second object
testObj.ref.a = "new val";

console.log(myObj.a); //new val
Azad
  • 5,144
  • 4
  • 28
  • 56
1

Primitive values are copied and Non primitive values such as objects and arrays are referenced. I think "myObject" will be referenced and myVar will be copied. To get the copy of myObject, you can clone it and assign it to the other variable.

Using JQuery:

{
  anObject: $.extend({},myObject), 
  aVar: myVar
}
varun
  • 652
  • 4
  • 5