I was asking myself if there is a way to add something like a subproperty to a variable. Here is an example of what I want to achive:
var variable = 5;
variable.property = "what ever...";
console.log(variable); //outputs 5
console.log(variable.property); //outputs "what ever..."
(The data types aren't important...)
Is there maybe a way to achive this using getters or Proxys, and does my variable need to be an object or not?
Hopefully you can help and there is a way to do this :)
You can add ad-hoc properties to any variable which points to an
Object
. You should also read up onprototype
if you're interested in using class-like objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototypeHowever, your example uses the number 5, which is a Primitive. You cannot assign properties to Primitives: https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
Also see this answer: https://stackoverflow.com/a/509780/71906