pol*_*ron 10 javascript prototype
我有这个类/功能
function Menu()
{
this.closetimer = 0;
this.dropdown = 0;
}
Menu.prototype.menuTimer = function()
{
this.closetimer = setTimeout(function()
{
this.menuClose();
}, this.timeout);
}
Menu.prototype.menuClose = function()
{
if(this.dropdown) this.dropdown.css('visibility','hidden');
}
Run Code Online (Sandbox Code Playgroud)
我想调用menuClose()属于Menu类的函数,但我认为这段代码实际上是试图menuClose()从closetimer对象调用.
如何menuClose()从内部引用Menu对象menuTimer()?
Nic*_*ver 16
在你的setTimeout()回调中,this指的是window,只需保留这样的引用:
Menu.prototype.menuTimer = function(){
var self = this;
this.closetimer = setTimeout(function(){
self.menuClose();
}, this.timeout);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是绑定内部函数.
Menu.prototype.menuTimer = function(){
this.closetimer = setTimeout(function(){
this.menuClose();
}.bind(this), this.timeout);
}
Run Code Online (Sandbox Code Playgroud)
Menu.prototype.menuTimer = function(){
this.closetimer = setTimeout(this.menuClose.bind(this), this.timeout);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11433 次 |
| 最近记录: |