有了這個劇本我添加變量的對象上運行: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