1

I have an object that is defined like this:

function company(announcementID, callback){
    this.url = 'https://poit.bolagsverket.se/poit/PublikSokKungorelse.do?method=presenteraKungorelse&diarienummer_presentera='+announcementID;
    self = this
    GM_xmlhttpRequest({
        method: "GET",
        url: this.url,
        onload: function(data) {
            self.data = data;
            callback();
        }
    })
}

on the callback, I wish to reference another method for that object called "callbacktest", I'm trying to do it like this?

    var mycompany = new company(announcementID, callbacktest);

if I would do it with an anonymous function, I would have written mycompany.callbacktest() but how do I reference "mycompany" from within its variables?

2 Answers 2

2

Until the reference is returned from the constructor to mycompany, you really can't access it for an argument.

So, I would say the "anonymous function" you alluded to is a good way to accomplish this as it will have access to the variable, which will have the reference:

var mycompany = new company(announcementID, function () {
    mycompany.callbacktest();
});

Or, maybe move the request work and callback to a method.

function company(announcementID){
    this.url = 'https://poit.bolagsverket.se/poit/PublikSokKungorelse.do?method=presenteraKungorelse&diarienummer_presentera='+announcementID;
}

company.prototype.request = function (callback) {
    var self = this;
    GM_xmlhttpRequest({
        method: "GET",
        url: this.url,
        onload: function(data) {
            self.data = data;
            callback();
            // or: callback.call(self);
        }
    })
};

company.prototype.callbacktest = function (...) { ... };

// ...

var mycompany = new company(announcementID);
mycompany.request(mycompany.callbacktest);

Note: You may need to .bind() the method when passing it to .request().

mycompany.request(mycompany.callbacktest.bind(mycompany));
Sign up to request clarification or add additional context in comments.

3 Comments

and add the httpRequest to a method
I just tried your second suggestion! It seems to work alltough console.log(this) does not return mycompany inside callbacktest, but rather the window-object
@KristofferNolgren I edited in a "Note" at the end that may be relevant to that. Did you see that yet? It may also benefit from mixing in Antti's answer.
1

If you want to have the constructed company as the this in callback, you can do so by:

// instead of callback(); do:
callback.call(self);

2 Comments

Why is this downwoted?
Ok thanks for downvote; he says he would want to say "mycompany.callbacktest()" but can't.

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.