On Jul 9, 10:11*pm, Lasse Reichstein Nielsen <l...@hotpop.comwrote:
"Adam C." <adam...@gmail.comwrites:
Mozilla.org suggests using the with statement to control bindings:
var f = 2;
with({f: 3}){
* eval("f"); // evaluates to 3
}
Ick. Don't use eval! Don't use with!
The above is the same as {f:3}["f"]
But that doesn't work for binding "this".
Indeed, "this" is not a variable, it's an operator.
setTimeout (with a string to be evaluated) will evaluate "this" as the
window.
eval.call(someObj, "this")
returns an error in Firefox; in IE is seems to just bind "this" to the
window.
Eval called as anything but a method on the global object is not
guaranteed to work.
The above is equal to just: someObj.
Is there a way to completely control the bindings, including this, of
the code to be evaluated?
Try:
*function myEval(thisObject, code) {
* *return (function(){return eval(code);}).call(thisObject);
*}
How would this work?
alert(myEval( {x:1}, "x"));
Would be a ReferenceError.
This isn't what you intended, is it? The - thisObject would be the
context, and would not be added to the [[Scope]] and certainly would
not augment the scope (as the OP's example using with does).
There might be a way of messing with Object.prototype and using a
catch clause:-
(function(){
var preexist = {};
function addToOp(o) {
var op = Object.prototype, p;
for(p in o) {
if(p in op)
preexist[p] = op[p];
op[p] = o[p];
}
}
function removeFromOp(o) {
var op = Object.prototype, p;
for(p in o) {
if(preexist.hasOwnProperty(p))
op[p] = preexist[p];
else
delete op[p];
}
}
this.ScopedEval = function(o, p) {
try { addToOp(o); throw 0; }
catch(f) {
ret = eval(p);
removeFromOp(o);
return ret;
}
}
})();
- but with would be much cleaner.
Garrett
But really ... try to avoid needing it instead!
Yes,
obj[prop] is the way to go!
>
/L