1

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

Anton Ballmaier
  • 876
  • 9
  • 25
  • you can set variable as { value: 5 } initially, then use variable.value to output 5 – Brian Jan 09 '17 at 18:05
  • @Brian Yeah, but that's not what I want... – Anton Ballmaier Jan 09 '17 at 18:08
  • If the variable is not a primitive type (e.g. `Number`, `String`, `Boolean`), then that will work (except that your second `var` keyword is not appropriate.) Everything else descends from `Object`, where this is normal. ([There are exceptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), BTW, but probably not important here.) It might not always be a good idea, but it should work. With primitives, you will be able to set the value, but it immediately disappears. – Scott Sauyet Jan 09 '17 at 18:08
  • Not directly on a primitive, though you can modify Number.prototype, this is also unadvisable if this question is for anything more than curiosity's sake. – Damon Jan 09 '17 at 18:18

1 Answers1

1

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

Community
  • 1
  • 1
James McCormack
  • 9,217
  • 3
  • 47
  • 57