Are functions valid keys for javascript object properties?

后端 未结 2 1429
误落风尘
误落风尘 2021-01-01 20:23

I\'d like to use functions as keys in a javascript object. The following works, at least in Chrome:

var registry = {};
function Foo(){  };
function Bar(){  }         


        
相关标签:
2条回答
  • 2021-01-01 20:58

    Everything you put between square brackets is converted into a string, and this happens even if you put a function, a date, a regexp... So there, you're actually creating an object like this:

    var registry = {
        "function Foo(){  }" : 42,
        "function Bar(){  }" : 43
    };
    

    This is a default behaviour, it works in IE too if you were wondering. It was actually exploited by John Resig in his famous addEvent function.

    0 讨论(0)
  • 2021-01-01 21:07

    ECMAScript 5.1 - Section 11.2.1:

    The production MemberExpression : MemberExpression [ Expression ] is evaluated as follows:

    1. Let baseReference be the result of evaluating MemberExpression .
    2. Let baseValue be GetValue(baseReference).
    3. Let propertyNameReference be the result of evaluating Expression.
    4. Let propertyNameValue be GetValue(propertyNameReference).
    5. Call CheckObjectCoercible(baseValue).
    6. Let propertyNameString be ToString(propertyNameValue).
    7. If the syntactic production that is being evaluated is contained in strict mode code, let strict be true, else let strict be false.
    8. Return a value of type Reference whose base value is base Value and whose referenced name is propertyNameString , and whose strict mode flag is strict.

    So when using obj[whatever], whatever is converted to a string. For a function this will be a string containing the sourcecode of the function.

    Example:

    js> var func = function() { return 'hi'; };
    js> function helloworld() { return 'hello world'; }
    js> var obj = {};
    js> obj[func] = 123;
    js> obj[helloworld] = 456;
    js> obj
    ({'function () {\n    return "hi";\n}':123,
      'function helloworld() {\n    return "hello world";\n}':456
    })
    
    0 讨论(0)
提交回复
热议问题