使用eval将字符串转换为函数是不是很邪恶? [英] is it evil to use eval to convert a string to a function?

查看:139
本文介绍了使用eval将字符串转换为函数是不是很邪恶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听过很多关于eval()的不同意见,并且有点不确定在这种情况下是否可以使用eval():

I have heard lot's of different opinions on eval() and are a bit unsure if it's ok to use eval() in this context:

让我们说我有像这样的对象:

let's say I have an object like this:

var bla = {
blubb: function (callback) {
       //GET some stuff via ajax
       //call the callback
    }
}

这样的字符串:

 var someString = "bla.blubb";

为了调用函数(和回调函数)来评估字符串是不是很邪恶?

Is it evil to eval the string in order to call the function (and the callback)?

var callMe = eval(someString)
callMe(function(){
   alert('yay')!
});


推荐答案


我听说很多对eval的不同意见()

i have heard lot's of different opinions on eval()

eval 一般来说不是邪恶的,它有应用程序。

eval is not evil in general, there are applications for it.


不确定在此上下文中是否可以使用eval()

unsure if it's ok to use eval() in this context

不,这不是好事。使用简单的括号记法成员运算符。由于每天都会询问SO,我可以在这里列出数百个欺骗(只是前几个谷歌搜索结果):

No, it is not OK for this. There is a much better solution using the simple bracket notation member operator. Since this is asked every day on SO, I can list hundreds of dupes here (just the first few Google results):

  • Convert string in dot notation to get the object reference
  • Convert javascript dot notation object to nested object
  • Accessing nested JavaScript objects with string key
  • access object through dot-syntax string path
  • Convert JavaScript string in dot notation into an object reference
  • Access object child properties using a dot notation string

这篇关于使用eval将字符串转换为函数是不是很邪恶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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