0

Are there any reasons why I should not do use a function reference as the property/key of a object ? This code works in Chrome, Firefox, & IE8, but "just because something works..."

var x = {}

var a = function() { return 'a' };
var b = function() { return 'b' };

x[a] = 1
x[b] = 2

x[a] === x[a] // returns true
x[a] === x[b] // returns false
x[b] === x[b] // returns true
x[a] // returns 1
x[b] // returns 2
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
  • Two different functions with the same body would serialize to the same string. This might not be desired. – Felix Kling Aug 23 '13 at 18:38
  • Oh FYI, ECMAScript 6 will introduce proper maps: http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets. Any value/object can be a key then. – Felix Kling Aug 23 '13 at 18:50

1 Answers1

5

Object Keys are string. What is used in x[a] is in fact x[a.toString()].

This means that your function as key is exactly the same key as a string :

x[a] === x["function () { return 'a' }"]

So yes, you might consider it both unsafe and unreasonable. It's hard to imagine a context in which it would be useful or efficient.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • See that's what I thought, about key's being strings, but Chrome's debugger was throwing me off since it doesn't show quotes about the keys. `var x = {'1': 'a'}; x;` prints out `Object {1: "a"}`. – Walter Stabosz Aug 23 '13 at 18:50