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)

3
  • object and var are reserved shouldn't used to be object's key Commented Dec 31, 2015 at 11:34
  • ok, will change that... it was just an example Commented Dec 31, 2015 at 11:35
  • since you specifically are asking about angular and object inheritance, I can't think of a better explanation than this answer: stackoverflow.com/a/14049482/2495283 Commented Dec 31, 2015 at 11:43

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.