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
|
Show 2 more comments
3 Answers
Reset to default 16It 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}']);
["function() {...}"]
– mplungjan Commented Mar 5, 2013 at 9:38