我想在命名空间内定义一个类类型,但我不知道如何执行此操作,以便“this”命令引用类的实例而不是命名空间的“this”。
如果我提供需要执行此操作的示例,将会更有意义。我正在创建一些 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);
如何将 Request 类放入 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);
最佳答案
你可以这样做:
var AjaxStack_f = function () {}
AjaxStack_f.prototype.Request = function(url, data, method) {
this.url = url;
this.data = data;
this.method = method;
}
然后你可以说:
var AjaxStack = new AjaxStack_f();
var request1 = new AjaxStack.Request("www.example.com", { value: 1 }, "get");
您不会遇到 this
是 Request
构造函数内的错误对象的问题,因为您正在使用 new
调用构造函数。
关于JavaScript 如何在命名空间内拥有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968786/