Is there a way to add "subproperties" to a variable in JS?

264 Views Asked by At

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 :)

1

There are 1 best solutions below

0
On BEST ANSWER

You can add ad-hoc properties to any variable which points to an Object. You should also read up on prototype if you're interested in using class-like objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

However, 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