Add metadata to JavaScript objects - Stack Overflow

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

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?

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?

Share Improve this question asked Jan 20, 2013 at 21:13 MaiaVictorMaiaVictor 53.1k47 gold badges158 silver badges302 bronze badges 2
  • 1 For objects, yes. For strings and numbers and booleans, no. You can always create your own map structure I guess, but I wouldn't call that "metadata" unless I really wanted to for some reason :-) – Pointy Commented Jan 20, 2013 at 21:18
  • 1 Functions are objects in JavaScript, so yes. – Pointy Commented Jan 20, 2013 at 21:23
Add a ment  | 

2 Answers 2

Reset to default 3

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.

You could do this :

var metaDataStorer = {};
function addMetadata(object, meta) {
    metaDataStorer[object] = meta;
}
function getMetadata(object) {
    return metaDataStorer[object];
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745217466a4617094.html

相关推荐

  • Add metadata to JavaScript objects - Stack Overflow

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

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信