怎么做" Object.defineProperty"在纯Rhino对象模型中?

时间:2014-04-10 16:30:55

标签: java javascript rhino

使用Rhino 17R4,我们可以使用Object.defineProperty()方法在javascript中创建属性。

public class MyGlobalObject : org.mozilla.javascript.ScriptableObject
{
    public static org.mozilla.javascript.Script ___compiledScript = null;
    public MyGlobalObject()
    {
        org.mozilla.javascript.Context con = org.mozilla.javascript.Context.enter();
        try
        {
            con.initStandardObjects(this);
            string strScript = "Object.defineProperty(this,\r\n 'onload', \r\n{  set : function(val){this.set_onload(val);},\r\n get : function(){return this.get_onload();}, enumerable: true, configurable: true});";

            this.defineFunctionProperties(new string[] { "set_onload", "get_onload" }, typeof(MyGlobalObject), org.mozilla.javascript.ScriptableObject.DONTENUM);
            org.mozilla.javascript.Script sc = con.compileString(strScript, "", 1, null);
            object result_onload = con.evaluateString(this, "this.onload == undefined;", "", 1, null); // make sure it is not defined.
            Console.WriteLine("onload is undefined? : {0}", result_onload);
            // Define Properties Now.
            sc.exec(con, this);


            con.evaluateString(this, "this.onload= function(){var t1 = 1;};", "", 1, null);
            object onloadobjectXYZ = con.evaluateString(this, "this.onload;", "", 1, null); // get function now.
            Console.WriteLine("Onload object : {0} is found", onloadobjectXYZ);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        org.mozilla.javascript.Context.exit();
    }
    private object __onloadFunction;
    public object get_onload()
    {
        Console.WriteLine("get_onload() called!");
        return this.__onloadFunction;
    }
    //[org.mozilla.javascript.annotations.JSSetter]
    public void set_onload(object _val)
    {
        Console.WriteLine("set_onload() called!");
        this.__onloadFunction = _val;
    }

    public override string getClassName()
    {
        return "Global";
    }

}

如何创建与" onloadobjectXYZ"相同的FunctionObject?在纯犀牛对象操作中(不是使用类似' strScipt'这样的脚本)?它似乎可以为setter和getter创建FunctionObject,但我找不到一个好的例子。有谁知道如何定义属性?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

使用java的defineProperty方法setter / getter与object.defineProprty()

略有不同
  this.defineProperty("onload", null, javaonloadGetMethod, javaonloadSetMethod, ScriptableObject.PERMANENT);

这对我来说是一种解决方法。

相关问题