這是我的理解,每個JavaScript對象都有一個原型,即使它只是一個Object.prototype當我不知道構造函數的名稱時,如何設置原型?
我有一個asp.net web服務代理,從服務器獲取參與者數據。這部分工作正常。下面的代碼:
atomWebServiceProxy.GetInteractionParticipants(interactionId,
function (participantsResult) {
var assetId, pendingPathFetches;
participants = participantsResult;
pendingPathFetches = participants.length;
document.title = participants.length + " participants:";
for (var i = 0; i < participants.length; i++) {
assetId = participants[i].ASSETID;
document.title += " " + participants[i].DISPLAYID;
atomWebServiceProxy.GetInteractionPath(interactionId, assetId,
function (pathResult, participant) {
participant.path = pathResult;
pathResult.participant = participant;
if (--pendingPathFetches == 0) {
setTimeout(afterInit, 20);
}
},
function (error, participant) {
alert(participant.DISPLAYID + " reported this error: " + error.get_message());
},
participants[i]
);
}
},
function (error) {
alert(error.toString());
});
您可能會注意到有嵌套調用和我添加了一個path屬性給每個參與者的對象,在對象模型中表達的事實,它是針對特定參與者的路徑數據。這也很好。
然後我試圖添加一個方法的原型是這樣的:
var foo = participants[0];
foo.prototype.redraw = function(map) {
... //code that redraws
};
令我非常驚訝的是,我得到了一個異常聲稱原型爲空:
JavaScript runtime error: Unable to set property 'redraw' of undefined or null reference
這是怎麼回事這裏?
This question似乎解決了這個問題,但我不明白如何將這些信息應用於這種情況,因爲我不知道如何引用未在我的代碼中定義的構造函數。
在這種情況下是有用的信息,在運行時立即窗口participants.constructor的檢查似乎表明構造爲陣列()
我應該寫一個構造函數,複製等領域爲對象並設置一個原型?如果是的話,是否存在與C#反射相當的JavaScript,所以我不必爲每種類型的查詢結果對象都重寫該函數?注意當我更新問題時,昏迷在評論中回答了這部分問題。
你試過'foo.constructor.prototype.redraw ='? – thebreiflabb 2013-05-06 08:39:52
它是JSON嗎?看看http://stackoverflow.com/questions/5873624/parse-json-string-into-a-particular-object-prototype-in-javascript – coma 2013-05-06 08:41:34
使用foo.constructor.prototype.redraw會導致jQuery-1.9.1在第2816行的barf說,處理程序是不確定的,我確實嘗試過。 – 2013-05-06 08:42:28