【发布时间】:2014-04-10 16:30:54
【问题描述】:
在 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";
}
}
如何在纯 rhino 对象操作中创建与“onloadobjectXYZ”相同的 FunctionObject(而不是使用像'strScipt'之类的脚本)?似乎它可以为 setter 和 getter 创建 FunctionObject,但我找不到一个很好的例子。有谁知道如何定义属性?
提前谢谢你!
【问题讨论】:
-
??这个问题没有多大意义。
-
您也可以将现有的 Java 代码放入问题中,以便我们知道您要为哪个(本机?)对象配备 getter/setter。
-
我更改了样本以避免混淆。我喜欢做的是创建 setter 和 getter 'onreadystatechange' 属性。
标签: java javascript rhino