0

For example, I have the following JS object:

var obj = {
 n: 0,
 o: {}
};
var nGlobal = obj.n;
var oGlobal = obj.o;

And want to use global variables in order to make it look like this:

var obj = {
 n: 5,
 o: {
 x: 7
 }
};

Obviously, I am able to assign a value to a property of oGlobal:

oGlobal.x = 7;

However, is there any way to change the value of obj.n through nGlobal, without mentioning obj?
Just something like this:

console.log(obj); // {n: 1, o: {}}
nGlobal.set(5);
// or
nGlobal.value = 5;
console.log(obj); // {n: 5, o: {}}
asked Nov 2, 2015 at 4:49
3
  • JavaScript is pass-by-value, not pass-by-reference. Assigning a value to a variable never changes the value of another variable or property (exception: global scope and with). Commented Nov 2, 2015 at 4:52
  • @FelixKling Or rather, for primitives: pass-by-value and non-primitives: pass-by-reference Commented Nov 2, 2015 at 4:53
  • 1
    @Tushar: No, objects are represented as references, but that has nothing to do with pass-by-reference. Pass-by-reference and pass-by-value refers to how variables and parameters related to each other. It has nothing to do with the values they hold. Commented Nov 2, 2015 at 4:53

1 Answer 1

2

Short answer:

No, there is not.

Long answer:

  1. In JS primitive types are immutable and passed by values.
  2. JS implements pass-by-value strategy, which means that ALL data is always passed by value (in case if you pass a reference to object - the reference is passed by value)

One important consequence from the items above: in JS there is no way to change the original object using the = operation. That is: you can modify an object when you have a reference to it, but you cannot swap one object with something else so that all other references also "were modified".

Related:

Credits:

answered Nov 2, 2015 at 4:50
Sign up to request clarification or add additional context in comments.

2 Comments

I know what you mean, but I think still think this should not be conflated. For example your answer could be interpreted that if obj.n was an object, nGlobal = someNewObject would magically work (but of course it does not). I guess what's more important here is that primitive values are immutable.
@FelixKling second attempt

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.