Javascript 如何访问原型&x27;从一个方法';s函数
我有这个类/功能Javascript 如何访问原型&x27;从一个方法';s函数,javascript,prototype,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(
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');
}
我想调用函数menuClose()
,它是Menu类的一部分,但我认为这段代码实际上试图从closetimer
对象调用menuClose()
如何从menuTimer()
中的菜单对象引用menuClose()
Menu.prototype.menuTimer = function(){
var self = this;
this.closetimer = setTimeout(function(){
self.menuClose();
}, this.timeout);
}
您可以在访问菜单时定义对该菜单的引用
Menu.prototype.menuTimer = function(){
var _self = this;
this.closetimer = setTimeout(function(){
_self.menuClose();
}, this.timeout);
}
另一种方法是绑定内部函数
您应该使用
var\u self
来防止与全局名称空间的冲突。这可以写为setTimeout(this.menuClose.bind(this),this.timeout)
?您完全正确,我已经更新了它来显示。这是迄今为止最好的解决办法。给我所有的选票!这听起来确实有点贪婪:-)与jQuery中prototype的bind函数等价的是$.proxy。非常有用。他们说jQuery写起来更短!:-P
Menu.prototype.menuTimer = function(){
this.closetimer = setTimeout(function(){
this.menuClose();
}.bind(this), this.timeout);
}
Menu.prototype.menuTimer = function(){
this.closetimer = setTimeout(this.menuClose.bind(this), this.timeout);
}