Rhino JavaScript 和动态作用域变量创建
我试图在 Rhino JavaScript 的函数中定义动态变量(特别是 Java 6 中嵌入的变量),但我不想诉诸 eval,也不想通过 this 引用它。基本上,我想获取一个对象,并将每个属性都转换为函数范围内的 var...类似:
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
不管你相信与否,如果我必须使用“this”,那就很重要了。 (它是一个动态生成的函数,我想用不同的上下文对象一遍又一遍地调用它,并且对每个变量使用“this”将非常有害)。
我还想避免必须获取新的引擎上下文或类似的东西...如果我可以直接在 JavaScript 中执行此操作,那就太好了(我认为结果会明显更快)。
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 function 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么,基本上你想要像 JS 的
with
一样工作的东西吗? *咧嘴笑,躲开,然后跑*请注意,一些著名的 JS 从业者,例如 Doug Crockford,强烈反对使用
with
。So, basically you want something that works like JS's
with
? *grins, ducks, and runs*Mind you, some well-known JS practitioners, like Doug Crockford, strongly deprecate the use of
with
.