最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Add metadata to JavaScript objects - Stack Overflow

programmeradmin0浏览0评论

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];
}
发布评论

评论列表(0)

  1. 暂无评论