So i am trying to learn object oriented programming in javascript.
function doStock() { //my class
var that = this;
var nAntiFreeze = null; // timeout ID
var getContent = function(oInPageContainer) {
GM_log('Antifreeze, before clear ' +nAntiFreeze);
//clearTimeout(nAntiFreeze);
GM_log('Antifreeze, after clear ' +nAntiFreeze);
};
return {
sLink : "",
oList : "",
sSplitOperator : ";",
reset : function() {
this.sLink = '';
this.oList = '';
this.sSplitOperator = ';';
nAntiFreeze = null;
},
loadPage : function() {
if (this.sLink.length == 0) return;
if (this.oList.length == 0) return;
nAntiFreeze = setTimeout(function(){GM_log(that); that.loadPage();},30000);
GM_log('antifreeze ' + nAntiFreeze);
getPageAsync2(this.sLink,false,getContent); //GM_xmlhttprequest
}
}
};
My script runs on GreaseMonkey in FireFox 4. In my code i am using the above function/class to make an object as follows.
var oStocker = new doStock();
oStocker.sLink = 'www.somepage.com';
oStocker.oList = 'some list, may be a string line or the array object';
oStocker.loadPage();
getPageAsync2
function calls GM_xmlhttprequest and then returns the result page contents inside a div container to the callback function.
First, general question: value of nAntiFreeze does not get reset to null or anything after i call clearTimeOut
function. Is this normal?
Second question: why when the timeout runs out, i get the error that.loadPage() is not a function
? GM_log(that) tells me [object Object].
A person on this question was able to make it work by using var that = this
. But why is it not working for me?
Custom Object calling Methods with setTimeout loses scope
EDIT: Third question: What happens if i create a million objects. Will browser get rid of them when they are done working? Because i sure am unable to free them as this object uses asynchronous ajax calls, which means that i can't do
var oStocker = new doStock();
oStocker.loadPage();
oStocker = null;
The oStocker = null will be called before my object even finished working.
Thanks