Javascript:使用setTimeout时对象的封装
如何使用setTimeout这样的函数来调用对象的成员函数,并在被调用函数内部使用this关键字?
请查看我的消息来源。我通过使用 Javascript closure 变量来模拟这一点。在我的例子中,被调用函数的参数 context 实际上是对象 o 的 this:
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();
是否可以保存 _hello() 函数的常用声明并使用关键字this,但不在内部使用context?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您尝试对经典 OOP 进行传统的私有成员隐藏,请使用以下方法:
另一种方法:
If you are trying to do traditional private member hiding from classical OOP, use the following:
Another approach:
好吧,我不明白这个问题,这是一些修改后的代码:
告诉我你的想法。
Ok, I didn't understand the question, here is the code after some modifications:
Tell me what you think.