lundi 30 août 2021

How to modify an object by its property reference?

I want to be able to increment the property of an object by having the reference of the property itself, but not the reference of the object itself.

I am sure this could be achievable through some sort of reflection, but not really familiar with the available resources in JavaScript to achieve so.

Sample code:

let myObject = {
  a: 1
}

// reference of my object property
let target = myObject.a

let test = (destination) => {

  // increment
  destination += 1 
   
  
}

test(target);
// prints {a: 1} - Does not work
console.log(myObject);

The following does not work because we are trying to modify the reference of the direct integer property, which is mutable aswell. destination would equal to 2, but the parent object myObject stays unchanged. Is there anyway to achieve, through reflection, alteration of myObject by just having the reference of one of its property, if we consider that a case whereas myObject would be outside of the function's scope?





Aucun commentaire:

Enregistrer un commentaire