Rhino JavaScript and dynamic scope var creation
I am trying to define a dynamic variable within a function in Rhino JavaScript (specifically what is embedded in Java 6), but I don't want to resort to eval, and I don't want to have to reference it via this. Basically, I want to take an object, and turn every property into a var within the scope of a function... something like:
var abc = "value";
var context = { abc: 123, xyz: "def" };
function test(cx) {
for (var p in cx) {
this_scope[p] = cx[p];
}
println(abc);
// DON'T WANT TO HAVE TO DO THIS:
// pritnln(this.abc);
}
test(context); // prints: 123
println(abc); // prints: value
Believe it or not, it is significant if I have to use "this." (it is a dynamically generated fu开发者_JS百科nction that I want to invoke over and over with different context objects and using "this" for every variable would be very detrimental).
I also want to avoid having to grab a new engine context or something like that... it would be superb if I can do this straight in JavaScript (I think the result would be significantly faster).
So, basically you want something that works like JS's with
? *grins, ducks, and runs*
var abc = "value";
var context = {abc: 123, xyz: "def"};
function test(cx) {
with (cx) {
println(abc);
}
}
test(context);
println(abc);
Mind you, some well-known JS practitioners, like Doug Crockford, strongly deprecate the use of with
.
精彩评论