Dynamic binding is bad, mmmkay? ;)
Seriously, it's not an efficiency thing. Dynamic scope is
easy to write but hard to predict. JS is lexically/statically
scoped almost everywhere, except for with, eval, and
the global object. Strict mode solves with and eval.
Isn't there another culprit that breaks static binding (without
introducing a new form of dynamic binding, though)?
Function.toString() does not account for closures, or any
static bindings really, rendering all variables by name.
We can thus use toString to break static binding, followed
by eval to rebind dynamically.
This is kind of expected for bindings in the function body,
but kind of odd for non-local bindings.
In the example below, static binding would suggest that
x,y, and world are bound to the global vars, even in the
function parameter to withE, right? But toString unbinds
them.
Claus
"use strict";
function log(msg) {
if (typeof console!=='undefined')
console.log(msg);
else if (typeof WScript!=='undefined')
WScript.Stdout.WriteLine(msg);
}
// this isn't really 'with', but ..
function withE(env,body) {
var code = "";
for(var e in env) {
if (env.hasOwnProperty(e))
code += "var "+e+"="+env[e]+";";
}
code += body.toString().replace(/^function\s*\([^)]*\)\s*/,"");
log(code);
return eval(code);
}
var x = "with", y = "hello", world = "world";
var result = withE({x:"'"+y+"'",y:"'"+x+"'",hello:"'"+y+"'"}
,function(hello){ x+", "+y+"! "+hello+", "+world+"!"; });
log(result);
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss