0

I'd like to define a class type inside my namespace, but I can't think how to do this so that the 'this' command referes to the instance of the class and not the 'this' of the namespace.

It will make more sense if I provide the example where I need to do this. I'm creating some JavaScript code to convert all forms to submit via Ajax instead, then if the Ajax request fails it attempts to submit the form again after a period of time. The thinking is so that the page will still work if the users internet connection drops.

Code

// 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();

Using the above I can do what I want to do with this code

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);

How can I put the Request class inside the AjaxStack namespace so that I can do something like this instead

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);
2
  • 1
    Am I the only one who finds that "Push a Request on to the stack" syntax a bit strange? Should it be AjaxStack_f.prototype.push = function(request){...}? Commented Aug 15, 2012 at 11:56
  • You are correct, sorry for the typo. Commented Aug 15, 2012 at 12:02

1 Answer 1

2

You can do this:

var AjaxStack_f = function () {}

AjaxStack_f.prototype.Request = function(url, data, method) {
    this.url = url;
    this.data = data;
    this.method = method;
}

Then you can say:

var AjaxStack = new AjaxStack_f();
var request1 = new AjaxStack.Request("www.example.com", { value: 1 }, "get");

You won't have a problem with this being the wrong object inside the Request constructor because you are calling the constructor with new.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was trying to do cheers, thanks for the insight about 'new'. Will give it while before accepting this as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.