我如何在 rhino 中定义全局 属性?
How can I define a global property in rhino?
我正在 Java 中嵌入 Rhino,我想创建一个带有 getter 和 setter 的全局 属性。此非全局 属性 定义有效:
var testObj = {};
Object.defineProperty(testObj, 'testPropName', {
set: function(value) { print('setter called w/' + value); }
});
如果我尝试使用全局 "this" 对象,它会抛出一个错误:
Object.defineProperty(this, 'testPropName', {
set: function(value) { print('setter called w/' + value); }
});
错误:
TypeError: Expected argument of type object, but instead had type object (#1) in at line number 1
从 Java 端创建它也可以,但我也没有运气。
Java 方面的解决方案...
public class MyCustomBindings extends SimpleBindings {
@Override
public Object put(String name, Object value) {
Object result = super.put(name, value);
// "setter" logic
return result;
}
@Override
public Object get(Object key) {
// "getter" logic
return super.get(key);
}
和其他地方...
ScriptEngineManager factory = new ScriptEngineManager();
engine = factory.getEngineByName("JavaScript");
MyCustomBindings bindings = new MyCustomBindings();
engine.getContext().setBindings(bindings, ScriptContext.ENGINE_SCOPE);
我正在 Java 中嵌入 Rhino,我想创建一个带有 getter 和 setter 的全局 属性。此非全局 属性 定义有效:
var testObj = {};
Object.defineProperty(testObj, 'testPropName', {
set: function(value) { print('setter called w/' + value); }
});
如果我尝试使用全局 "this" 对象,它会抛出一个错误:
Object.defineProperty(this, 'testPropName', {
set: function(value) { print('setter called w/' + value); }
});
错误:
TypeError: Expected argument of type object, but instead had type object (#1) in at line number 1
从 Java 端创建它也可以,但我也没有运气。
Java 方面的解决方案...
public class MyCustomBindings extends SimpleBindings {
@Override
public Object put(String name, Object value) {
Object result = super.put(name, value);
// "setter" logic
return result;
}
@Override
public Object get(Object key) {
// "getter" logic
return super.get(key);
}
和其他地方...
ScriptEngineManager factory = new ScriptEngineManager();
engine = factory.getEngineByName("JavaScript");
MyCustomBindings bindings = new MyCustomBindings();
engine.getContext().setBindings(bindings, ScriptContext.ENGINE_SCOPE);