声明javascript对象时在其变量中引用它

声明javascript对象时在其变量中引用它,javascript,Javascript,我有一个对象定义如下: function company(announcementID, callback){ this.url = 'https://poit.bolagsverket.se/poit/PublikSokKungorelse.do?method=presenteraKungorelse&diarienummer_presentera='+announcementID; self = this GM_xmlhttpRequest({

我有一个对象定义如下:

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();
        }
    })
}
在回调中,我希望引用另一个对象的方法“callbacktest”,我试着这样做

    var mycompany = new company(announcementID, callbacktest);

如果使用匿名函数,我会编写mycompany.callbacktest(),但如何从其变量中引用“mycompany”?

如果您希望将构建的公司作为回调中的
this
,您可以通过以下方式执行:

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

在构造函数将引用返回到mycompany之前,您确实无法访问它作为参数

因此,我想说,您提到的“匿名函数”是实现这一点的一个好方法,因为它可以访问变量,该变量将具有以下引用:

var mycompany = new company(announcementID, function () {
    mycompany.callbacktest();
});
或者,可以将请求工作和
回调
移动到一个方法

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);
注意:在将方法传递给
.request()
时,可能需要使用该方法


这是为什么?好的,谢谢你的否决票;他说他想说“mycompany.callbacktest()”,但不能。我刚刚试过你的第二个建议!它似乎在所有艰难的控制台中都能正常工作。log(this)不会返回mycompany inside callbacktest,而是返回窗口-object@KristofferNolgren我在结尾处编辑了一个可能与此相关的“注释”。你看到了吗?它也可以从混合中受益。
mycompany.request(mycompany.callbacktest.bind(mycompany));