函数是javascript对象属性的有效键吗? [英] Are functions valid keys for javascript object properties?
问题描述
我想在javascript对象中使用函数作为键。以下工作至少在Chrome中有效:
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(){ };
registry[Foo] = 42;
registry[Bar] = 43;
alert(registry[Foo] + " < " + registry[Bar]);
标准涵盖了这个吗?它支持哪些浏览器?
Is this covered by the standard? By which browsers is it supported?
推荐答案
您放在方括号之间的所有内容都会转换为字符串,即使您发生这种情况也会发生放一个函数,一个日期,一个正则表达式......那么,你实际上是在创建一个这样的对象:
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
};
这是一种默认行为,如果你想知道它也适用于IE。它实际上是由John Resig在他的着名的 addEvent $ c $中利用的。 c>功能
。
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.
这篇关于函数是javascript对象属性的有效键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!