Really use eval to convert a string to a function?

I heard a lot of different opinions about eval () and I'm a little unsure if using 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
    }
}

And a line like this:

 var someString = "bla.blubb";

Is it an evil value to evaluate a string to call a function (and a callback)?

var callMe = eval(someString)
callMe(function(){
   alert('yay')!
});
0
source share
4 answers

I heard a lot of different opinions about eval ()

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

not sure if it is ok to use eval () in this context

, . , . SO, ( Google):

+5

, ( ).

, , someString. , , - ( ) .

eval. . :

window.a = {b:{c:function(){console.log('here')}}};
var someString = "a.b.c";

var path = someString.split('.');
var f = window;
for (var i=0; i<path.length; i++) f = f[path[i]];
f.call(null);

( ), .

+1

, . - :

function getValue(namespace, parent) {
    var parts = namespace.split('.'),
        current = parent || window;
    for (var i = 0; i < parts.length; i += 1) {
        if (current[parts[i]]) {
            current = current[parts[i]];
        } else {
          if (i >= parts.length - 1)
            return undefined;
        }
    }
    return current;
}
var foo = {
    bar: {
        baz: function () { alert('baz'); }
    }
};
var f = getValue('foo.bar.baz'); //true
if (typeof f === 'function') {
    f();
}

, eval('foo.bar.baz'), , , .

, jsperf:

0

, " eval" javascript, , .

:

this.foo = { bar:function(){return "baz"}};

// some code.
var obj = "foo";
var param = "bar";

this[obj][param](); // same as this.foo.bar();

(, ), eval .

0

All Articles