如何从方法的函数中访问原型的父级 [英] How to access a prototype's parent this from within a method's function

查看:40
本文介绍了如何从方法的函数中访问原型的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程/功能

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

我想调用Menu类的一部分函数 menuClose(),但是我认为这段代码实际上是试图从调用 menuClose()> closetimer 对象.

I want to call the function menuClose() which is part of the Menu class, but I think this code actually tries to call menuClose() from the closetimer object.

如何从 menuTimer()中的Menu对象引用 menuClose()?

How do I reference menuClose() from the Menu object from within menuTimer()?

推荐答案

在您的 setTimeout() 回调, this 引用 window ,只需保留这样的引用即可:

In your setTimeout() callback, this refers to window, just keep a reference like this:

Menu.prototype.menuTimer = function(){
    var self = this;
    this.closetimer = setTimeout(function(){
        self.menuClose();
    }, this.timeout);
}

这篇关于如何从方法的函数中访问原型的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆