I have following javaScript \"class\":
A = (function() {
a = function() { eval(...) };
A.prototype.b = function(arg1, arg2) { /* do something... */};
}
I was struggling with this for a while in Angular, and found this answer the most useful. I was trying to implement some existing code which use 'with', not allowed by strict. My 'knife and fork' solution to not having to use 'this.' inside the expression I wanted to evaluate, and avoiding 'with' and 'eval' was:
let evalInContext = function (js, context) {
let keys = Object.keys(context);
//let code = 'function it(){';
let code = '';
for (let i = 0; i < keys.length; i++){
code += 'let '+keys[i]+' = window._evalincontextobj.'+keys[i]+';\n';
}
code += 'return (';
code += js;
code += ')';//}\n return it();';
window['_evalincontextobj'] = context;
let res = Function(code)();
console.log(js+' = '+res);
delete window['_evalincontextobj'];
return res;
}
This is working for expressions like (watched === 'hello') where 'watched' is a member of context.