sergzach
sergzach

Reputation: 6754

Javascript: Encapsulation of an Object When Using setTimeout

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?

Upvotes: 0

Views: 732

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185913

Ok, I didn't understand the question, here is the code after some modifications:

var Utils = {
    Caller: function ( context, func ) {
        this.exec = function () {
            func.call( context );
        };
    }
};

function Obj() {
    this._s = 'Hello, World!';

    this._hello = function () {
        alert( this._s );
    }

    this.startTimer = function () {
        var caller = new Utils.Caller( this, this._hello );
        setTimeout( caller.exec, 1000 );
    };  
}

var o = new Obj();
o.startTimer();

Tell me what you think.

Upvotes: 1

Ryan
Ryan

Reputation: 1557

If you are trying to do traditional private member hiding from classical OOP, use the following:

    function MyObj() {

        // setup private closure scope
        var that = this;  // keep reference to this in constructor closure scope
        var s = "Hello, World!";
        var hello = function() {
            alert(s);
        };

        // expose public methods  
        this.startTimer = function() {
            setTimeout(function() {
                hello();
            }, 1000);
        };
    }

    var o = new MyObj();
    o.startTimer();

Another approach:

    function MyObj() {
        var that = this;
        this._s = "Hello, World!";
        this._hello = function() {
            alert(this._s);
        };
        this.startTimer = function() {
            setTimeout(function() {
                hello.call(that);
            }, 1000);
        };
    }

Upvotes: 1

Related Questions