可以安全地使用函数引用作为对象属性/键 [英] Is is safe to use function reference as an object property/key

查看:117
本文介绍了可以安全地使用函数引用作为对象属性/键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么原因我不应该使用函数引用作为对象的属性/键?此代码适用于Chrome,Firefox和IE8,但只是因为有用的工作...

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


推荐答案

对象键是字符串。 x [a] 中使用的是 x [a.toString()]

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.

这篇关于可以安全地使用函数引用作为对象属性/键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆