How to use such functions as setTimeout to call member functions of objects with using of this keyword inside of called functions?
Look to my source please. I simulate this by using Javascript closure variables. In my case called function has argument context that is actually this for the object o:
var Utils =
{
Caller: function( context, func )
{
var _context = context;
var _func = func;
this.call = function()
{
_func( _context );
};
return this;
}
};
// example of using:
function Object()
{
this._s = "Hello, World!";
this.startTimer = function()
{
var caller = new Utils.Caller( this, this._hello );
setTimeout( caller.call, 1000 );
};
this._hello = function( context )
{
alert( context._s );
}
}
var o = new Object();
o.startTimer();
Is it possible to save usual declaration of _hello() function and use keyword this, but not to use context inside?
Function.apply/Function.callandFunction.bind. N.B.: your customCaller.callfunction will shadow the native one; be careful!Objectreferences the built-inObjectconstructor. You don't want to shadow it...return this;insideCalleris not necessary since you're using it as a constructor anyways.new), thethisvalue will be returned by default. Example