Take a look at this code snippet:
<html>
<head>
<script type="text/javascript">
function abc(){
var v = 9;
var w = 2;
var x = 7;
var template = '{w} + {x} = {v}';
var func = eval('(' + def.toString() + ')');
func(template);
}
function jkl(){
var v = 1;
var y = 'hello';
var z = 'world';
var template = '{v}. {y} {z}';
var func = eval('(' + def.toString() + ')');
func(template);
}
function def(template){
var re = /{(.+?)}/;
var match = template.match(re);
while (match != null){
template = template.replace(re, eval(match[1]));
match = template.match(re);
}
alert(template);
}
</script>
</head>
<body>
<input type="button" value="abc" onclick="abc()"/><br/>
<input type="button" value="jkl" onclick="jkl()"/><br/>
</body>
</html>
This piece of code includes two functions (abc and jkl) as well as a parsing function def which takes a string template as input and parses it using variables from the calling function(abc or jkl).
Function def needs to have access to all the variables known to the calling function.
To address this issue, I added the following line in abc and jkl:
var func = eval('(' + def.toString() + ')');
This essentially redefines def as func within the calling function, allowing it to be treated as a sub-function of the caller and bringing it into the same scope.
While this solution works well, it is not ideal as converting def to a string and re-evaluating it as a function every time it's needed can be cumbersome. I am open to suggestions for a better approach if one exists.
I prefer not to pass all variables as parameters to def because:
- The template being parsed could be large and contain numerous variables.
- If all variables are passed as parameters to def and accessed using the arguments array, it would require using array notation inside the template, which is not recommended.
- Creating a hash map object with all the variables and passing that object as an argument to def is possible but would involve significant coding overhead to populate the hash map with caller's variables before each call to def.
Note: Please refrain from mentioning any imperfections in the parsing function, as this is just a simplified version of my actual code.