我在Java中嵌入Rhino,我想用getter和setter创建一个全局属性。此非全局属性定义有效:
var testObj = {};
Object.defineProperty(testObj, 'testPropName', {
set: function(value) { print('setter called w/' + value); }
});
如果我尝试全球"这个"对象会抛出错误:
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端创建它也没关系,但我也没有运气。
答案 0 :(得分:0)
来自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);