Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add metadata to JavaScript objects

Is it possible to add metadata to JavaScript objects (including strings, numbers and functions)? That is,

double = function(a){ return a*2; };
addMetadata(double,{desc:"Returns the double of a number."});
getMetadata(double).desc;

How could addMetadata and getMetadata be implemented?

like image 502
MaiaVictor Avatar asked May 27 '26 15:05

MaiaVictor


1 Answers

For objects, including functions, the best way to implement get/setMetadata is not to implement it at all.

double = function(a){ return a*2; };
double.desc = "Returns the double of a number."
alert(double.desc);

For "primitive" strings/numbers you can use a dictionary approach like suggested in another answer:

metaStorage = {}

setMetaData = function(obj, data) {
    if(typeof obj == "object")
        obj._metaData = data;
    else
        metaStorage[obj] = data;
}

getMetaData = function(obj) {
    if(typeof obj == "object")
        return obj._metaData;
    else
        return metaStorage[obj];
}

setMetaData(1, "this is one");
console.log(getMetaData(1))


setMetaData(window, "my window");
console.log(getMetaData(window))

However, I can't imagine how it could be useful to attach metadata to string/number literals.

like image 195
georg Avatar answered May 30 '26 06:05

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!