Are functions valid keys for javascript object properties?

后端 未结 2 1461
误落风尘
误落风尘 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题