3

在 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.setPrototypeContext.javaToJS

4

1 回答 1

4
    public Scriptable jsGet_member() {
        Scriptable scope = ScriptableObject.getTopLevelScope(this);
        Member m = new Member();
        m.setParentScope(scope);
        // defineClass("Member") must have previously been called.
        m.setPrototype(ScriptableObject.getClassPrototype(scope, "Member"));
        m.defineFunctionProperties(new String[] { "toString" },
                m.getClass(), DONTENUM);
        return m;
    }

js> defineClass("Member")
js> defineClass("Hosted")
js> var h = new Hosted();
js> var m = h.member;
js> m.toString();
called toString()
js> m instanceof Member;
true
js> m.__proto__;
[object Member]

编辑:该方法也可以写成:

    public Scriptable jsGet_member() {
        Scriptable scope = ScriptableObject.getTopLevelScope(this);
        Context cx = Context.getCurrentContext();
        Member m = (Member)cx.newObject(scope, "Member");
        m.defineFunctionProperties(new String[] { "toString" },
                m.getClass(), DONTENUM);
        return m;
    }

这将调用 Member.jsConstructor;可能还有其他差异。

于 2009-03-27T20:38:02.237 回答