I have function source stored in a string eg.:
var source="(function(){return Math.sin(x);})";
I want to pass it to eval() and calculate it’s value later:
var f=eval(source);
var v=f();
It works well. However, I want to be able to use functions from Math without Math. prefix. So I would be able to do:
var source="(function(){return sin(x);})";
Is there a simple way to achieve this? I already use WebGL, so it doesn’t have to be compatible with older browsers.
Additional info:
I’m aware that eval() is bad. I’m writing function grapher, source is function entered by the user that is going to be drawn. That’s also why want to get rid of Math. prefixes.
I know it’s not going to be pretty but I’m not going to write my own parser. Maybe there is some better way?
You can use the ancient, slow, ugly
withkeyword to extend the scope:See also: https://developer.mozilla.org/en/JavaScript/Reference/Statements/with