开发者

Javascript: Encapsulation of an Object When Using setTimeout

开发者 https://www.devze.com 2023-04-13 07:39 出处:网络
How to use such functions as setTimeout to call member functions of objects with using of this keyword inside of called functions?

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 开发者_如何学Goo = new Object();
o.startTimer();

Is it possible to save usual declaration of _hello() function and use keyword this, but not to use context inside?


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);
        };
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消