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
Firstly,
nAntiFreezeis a primitive value returned bysetTimeout. You pass that value back toclearTimtoutso it knows which timeout to clear. CallingclearTimeoutdoesn’t affect the value ofnAntiFreeze.Secondly,
that.loadPageis undefined becausethatreferencesthiswhendoStock()is called (where it is called as a constructor withnew, it references a new Object). But your function doesn’t return that object (i.e. the constructor’sthis), it returns the object afterreturnthat theloadPage()function is a method of. In other words, you are referencing the wrong object.When you call
oStocker.loadPage(), itsthiskeyword references theoStockerobject, but the function passed to setTimeout is referencingthat, which has a closure to the constructor’sthis.The following should work:
There isn’t much point using a constructor that doesn’t return its
this, you can use Richard Cornford’s module pattern and use closures for inheritance.