1

I've few variables that are of type number (or for that matter strings too). I want add some metadata to these variables.

When I try to use Object.defineProperty(myvar, "prop", {/*getter & setter*/}) it gives an error that myvar is not an object.

How can I define a property on non-objects with getter and setter methods?

I don't want to add anything to Number.prototype because I want these properties only on few variables.

Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32
  • Wouldn't be putting objects into an array and using the numeric index be the usual way to deal with this? – Filburt Oct 28 '15 at 10:21
  • Use `Number` and `String` objects instead of primitives if you really really insist on properties. No, you cannot put properties on non-objects *by definition*. – Bergi Oct 28 '15 at 11:08

1 Answers1

1

You can do this by prototypal inheritance. Using Number.prototype like this:

var proto = Object.create(Number.prototype);
function MyNumber() {
}
MyNumber.prototype = proto;
MyNumber.prototype.constructor = MyNumber;
MyNumber.prototype.someOwnMethod = function () {
}
// and so on
var myVar = new MyNumber();
Object.defineProperty(myvar, "prop", {/*getter & setter*/});

You'll get an Object in prototypes along with methods of Number.

Or if you do not need any own methods, just use Number constructor instead of number literal.

var myVar = new Number();
Object.defineProperty(myvar, "prop", {/*getter & setter*/});

The same for strings:

    var myVar = new String();
Romko
  • 1,808
  • 21
  • 27
  • The function that I'm writing takes JSON object as parameter and this JSON has different properties that are of primitive type. I wanted to add metadata to these properties without changing the datatypes of these properties or adding anything to prototype. As there is no way to add metadata to primitive types, now I'm creating a new JSON object in my method with identical structure of input param but for the values I'm using the equivalent Objects of primitive types and returning this new JSON object from my method. So that the input object remains intact. – Vivek Athalye Oct 30 '15 at 05:58