0

I have the following function that should create a function from a String with event -

function getFuncDefEvent(jsFunctionString){
    if(jsFunctionString!= undefined) {
        return function(event){jsFunctionString};
    }
}

this would be an example of a function string :

 jsFunctionString = "doSomething(event); doSomethingElse();

I've attached it to a onclick event however it doesn't seem to fire any of the events. Am I missing something?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
AkinW
  • 143
  • 10
  • What do you expect a String to do? I suspect you'd need to use [`eval()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval) for this, but it does have its security problems with untrusted code (and any user-accessible, user-editable, code is or should be untrusted). Possible duplicate: http://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript – David Thomas Oct 13 '16 at 12:23

2 Answers2

3

That's not how you create a function from a string. You need to use the Function constructor:

return new Function(['event'], jsFunctionString);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

edit: On review, I think Barmar's answer is probably more correct than my answer below. I'll leave it for posterity, but his is probably the one that should be selected as correct.




That's not how Javascript works. If you want to evaluate arbitrary strings as Javascript code you'll have to use eval. Please note, however, that much of the prevailing wisdom is that eval is evil.

Community
  • 1
  • 1
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45