我想在命名空間中定義一個類的類型,但我無法考慮如何執行此操作,以便'this'命令反映類的實例,而不是命名空間中的'this'。JavaScript如何在命名空間中使用類
如果我提供了我需要這樣做的例子,它會更有意義。我創建了一些JavaScript代碼來將所有表單轉換爲通過Ajax提交,然後如果Ajax請求失敗,它將嘗試在一段時間後再次提交表單。這個想法是這樣的,如果用戶的網絡連接斷開,該頁面仍然可以工作。
代碼
// Add event handlers to capture form submit events here (code not shown)
// Use this object as a namespace
var AjaxStack_f = function() {}
// Use this as a struct/class for defining requests (This is what I don't like)
function Request(url, data, method) {
this.url = url;
this.data = data;
this.method = method;
}
// The stack of Requests
AjaxStack_f.prototype.stack = [];
// Push a Request on to the stack
AjaxStack_f.prototype.push = function(request){
this.stack.push(request);
}
// Provide instance
var AjaxStack = new AjaxStack_f();
使用上面,我可以做我想做這個代碼
var request1 = new Request("www.example.com", { value: 1 }, "get");
var request2 = new Request("www.anotherurl.com", { value: 2 }, "get");
AjaxStack.push(request1);
AjaxStack.push(request2);
我怎樣才能把請求類AjaxStack命名空間中,這樣我可以做的事做這樣反而
var request1 = new AjaxStack.Request("www.example.com", { value: 1 }, "get");
var request2 = new AjaxStack.Request("www.anotherurl.com", { value: 2 }, "get");
AjaxStack.push(request1);
AjaxStack.push(request2);
我是唯一一個發現「將請求推入堆棧」的語法有點奇怪嗎?它應該是'AjaxStack_f.prototype.push = function(request){...}'? – nnnnnn 2012-08-15 11:56:52
你是對的,抱歉的錯字。 – Ally 2012-08-15 12:02:26