在 Rhino 中将宿主对象返回到 JavaScript 的最佳方法是什么?我有两个这样的课程:
public class Hosted extends org.mozilla.javascript.ScriptableObject {
private static final long serialVersionUID = 1;
public Hosted() {}
public void jsConstructor() {}
public String getClassName() {
return "Hosted";
}
public Member jsGet_member() {
Member m = new Member();
m.defineFunctionProperties(new String[] { "toString" }, m.getClass(), DONTENUM);
return m;
}
}
public class Member extends org.mozilla.javascript.ScriptableObject {
private static final long serialVersionUID = 2;
public Member() {}
public void jsConstructor() {}
public String getClassName() {
return "Member";
}
public String toString() {
return "called toString()";
}
}
从某种意义上说,它可以调用 toString 方法,但成员对象的行为与我预期的不同:
js> defineClass("Hosted");
js> defineClass("Member");
js> var h = new Hosted();
js> h.toString();
[object Hosted]
js> h instanceof Hosted;
true
js> h.__proto__;
[object Hosted]
js>
js> var m = h.member;
js> m.toString();
called toString()
js> m instanceof Member; // Should be true
false
js> m.__proto__; // Should be [object Member]
null
如果我打电话Object.prototype.toString
,它确实说它是一个成员对象:
js> Object.prototype.toString.call(m);
[object Member]
我试过打电话m.setPrototype
和Context.javaToJS
。