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

Is it completely valid to have a javascript function as key in an object? - Stack Overflow

programmeradmin1浏览0评论

Is it completely valid to have a javascript function as key in an object?

The following works, but I'm not sure it' s 100% (ecma or whatever body governs this) compliant

var f = function(){

};

var obj = {};

obj[f] = "a";


console.log(obj[f]);

Is it completely valid to have a javascript function as key in an object?

The following works, but I'm not sure it' s 100% (ecma or whatever body governs this) compliant

var f = function(){

};

var obj = {};

obj[f] = "a";


console.log(obj[f]);
Share Improve this question asked Mar 5, 2013 at 9:33 Geert-JanGeert-Jan 18.9k19 gold badges81 silver badges145 bronze badges 7
  • 4 I'm very curious to see a practical use-case for this. – lc. Commented Mar 5, 2013 at 9:35
  • I would say it is sort of pointless. the function is likely using toString to create a key of ["function() {...}"] – mplungjan Commented Mar 5, 2013 at 9:38
  • 2 keeping track / deregistering of anonymous subscriber-functions in a pub/sub-system. Not sure this is the right datastructure for the job though – Geert-Jan Commented Mar 5, 2013 at 9:40
  • @mplungjan: hmm you' re absolutely right, just tested it. So no it does not work. – Geert-Jan Commented Mar 5, 2013 at 9:42
  • 1 could be useful for caching the result of some functions – Enrique Commented Feb 16, 2019 at 19:51
 |  Show 2 more comments

3 Answers 3

Reset to default 16

It looks as it working, but it might not work as you expected.

The function is casted to string when used as a key:

var f = function(a) { return a; };
var obj = {};
obj[f] = 'abc';
console.log(JSON.stringify(obj));
//"{"function (a) { return a; }":"abc"}"
console.log(f.toString());
//"function (a) { return a; }"
var f2 = function (a) { return a; };
console.log(obj[f2]);
//"abc"

So, functions f and f2 are different objects, but they are the same when casted to string.

There is zero reason to do that, since object keys in ECMAscript may only be strings (for the time being, in ECMAscript 262 edition 3 and 5, by spec).

Things will change however in ECMAscript 6, where we will have WeakMaps and object keys also can be objects (I'm not sure about function references).

Even if a browser can distinguish object keys by function reference right now, its definitely questionable behavior, most likely experimental and should not be used right now.

var f = function(){

};
var obj = {};
obj[f] = "a";
console.log(obj['function (){\r\n\r\n}']);
发布评论

评论列表(0)

  1. 暂无评论