Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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]);
like image 345
Geert-Jan Avatar asked Mar 05 '13 09:03

Geert-Jan


People also ask

Can JavaScript function object be key?

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.

Can a function be a property of an object JavaScript?

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.

Can objects contain functions JavaScript?

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.

Can JavaScript objects have numbers as keys?

Each key in your JavaScript object must be a string, symbol, or number.


2 Answers

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.

like image 185
SWilk Avatar answered Sep 20 '22 12:09

SWilk


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.

like image 38
jAndy Avatar answered Sep 21 '22 12:09

jAndy