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]);
The Object keys() function returns the array whose elements are strings corresponding to the enumerable properties found directly upon the object. An ordering of the properties is the same as that given by an object manually in the loop is applied to the properties.
Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.
Object properties can be both primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.
Each key in your JavaScript object must be a string, symbol, or number.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With