有了这个剧本我添加变量的对象上运行:JavaScript的动态变量
function MyDocument(someDocument)
{
if(!(someDocument instanceof KnownDocumentClass))
throw "Object must be an instance of KnownDocumentClass: " + someDocument;
this.Document = someDocument;
this.Fields = {};
this.updateValues = function()
{
for (var _it = this.Document.iterator(); _it.hasNext();)
{
var _property = _it.next();
try
{
this[_property.getQualifiedName()] = _property.getContent();
}
catch(err)
{
log("Error :"+err);
}
}
}
this.updateValues();
}
因此,例如,我可以用
var mydoc = new MyDocument(knownjavadoc);
log(mydoc.Creator) // Shows the original content.
此内容可以有多个类型(一些是int
,一些String
和许多其他自定义Java类)。因此,它可以发生log(mydoc.SomeProperty)
回报:
PropertyObjectImpl[id=abc123, data=Some Data, type=Node, order=42]
我知道,我可以将函数添加到MyDocument
像
this.getValueAsString = function(name)
{
var _prop = this[name];
if(_prop instanceof PropertyObjectImpl)
return "PropertyObject with ID : " + _prop.getID();
else
return _prop;
}
但对于锻炼目的,我想这个功能直接添加作为toValueString()
这些属性,以便拨打电话:
var value = mydoc.SomeProperty.toValueString()
而不是
var value = mydoc.getValueAsString("SomeProperty");
这可能吗?
我不会建议重新定义toString,因为它不会触摸你不拥有的物体(比如像jQuery这样的PrototypeJs库)。标准/本机对象应该按预期行事。 – pbo
感谢您的回答,不是一个坏主意,但像pbo说的,我不想覆盖所有这些对象的默认toString()。 – Kooki
@Kooki,看到我的第二个编辑 – series0ne