Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How change object properties without reassign them

Tags:

javascript

The snippet below exposes the doubt

var foo = 'something'
var baz = 'other thing'

var obj = {
  prop1 : 'my prop',
  prop2 : foo,        //referencing external variable
  prop3 : baz         //referencing external variable
}

// here we get the expected obj to be printed
console.log(obj)

// now I change one of the initial variable
foo = 'changed'

// here we get the sabe print as the first, that is the ~problem~   
console.log(obj)

So, how to print 'changed' on prop2 without reassign obj.prop2 = foo

like image 473
Leandro Ferreira Fernandes Avatar asked Sep 09 '17 14:09

Leandro Ferreira Fernandes


2 Answers

When you do

var obj = {
  prop1 : 'my prop',
  prop2 : foo,        //referencing external variable
  prop3 : baz         //referencing external variable
}

there is no ongoing link between prop2 and the variable foo (or prop3 and baz). All that happens is that the current value of foo is read, and stored in prop2 (and the same for baz and prop3).

If you need prop2 and prop3 to remain linked to foo and baz, you could make them properties with getters. These are properties that trigger a function call when they're read (there are also setters which trigger a function call when the property is set):

var obj = {
  prop1 : 'my prop',
  get prop2() { return foo; },
  get prop3() { return baz; }
};

Accessing obj.prop2 is a hidden function call. Since the function closes over foo, it returns foo's current value.

Live Example:

var foo = 'something';
var baz = 'other thing';

var obj = {
  prop1 : 'my prop',
  get prop2() { return foo; },
  get prop3() { return baz; }
};

console.log(obj);

foo = 'changed';

console.log(obj);
like image 77
T.J. Crowder Avatar answered Oct 19 '22 15:10

T.J. Crowder


Since JavaScript is pass by value instead of pass by reference you cannot override the previous value by assigning it directly to the variable.

You can though make an object of it, and change a property of the object like this:

var foo = {value: 'something'}
var baz = 'other thing'

var obj = {
  prop1 : 'my prop',
  prop2 : foo,        //referencing external variable
  prop3 : baz         //referencing external variable
}

console.log(obj)

foo.value = 'changed'
 
console.log(obj)
like image 32
Ivar Avatar answered Oct 19 '22 15:10

Ivar