【问题标题】:Get the name of a method stored in a variable获取存储在变量中的方法的名称
【发布时间】:2015-10-28 10:02:04
【问题描述】:

我在获取存储在变量中的方法名称时遇到了一些麻烦...这是我想要的一个示例:

Function MyObject(){
    this.actualMethod = this.thatName;
}

MyObject.prototype.thatName = function(){}

MyObject.prototype.getActualMethodName = function(){
    return this.actualMethod.name; /* This doesn't work since the function itself is anonymous, so this.actualMethod.name doesn't work... I want it to return "thatName" */
}

我试图用我的控制台浏览原型,但徒劳无功......有没有办法做到这一点?

【问题讨论】:

  • 有什么问题?就return this.actualMethod;

标签: javascript inheritance methods


【解决方案1】:

你需要给函数命名:

MyObject.prototype.thatName = function thatName() {};

或者,正如您所提到的,您可以在原型中找到它的名称(但我不建议您这样做):

for (var key in MyObject.prototype) {
  if (MyObject.prototype[key] === this.actualMethod) {
    return key;
  }
}

但是你为什么需要这个?也许会有更好的解决方案。

【讨论】:

  • 为函数命名(解决方案 1)是一种好习惯吗?我以前从未见过这个......但第二个解决方案似乎有效=)!我不知道可以像这样迭代......看起来很简单!
  • 我从事一个涉及在画布上操纵正方形的项目。 “Onmousedown”,我选择了一个方法来调用(“move”,“resize”...),鼠标的位置在正方形旁边。 “onmousemove”,选择的方法被调用(如果鼠标仍然按下),所以我需要将它存储在一个变量(“this.actualMethod”)中才能调用它onmousemove。 “Onmouseup”,我想调用一个回调函数。我有一个看起来像这样的函数数组:{'move':function(){/*dostuff*/},'resize':function{/*otherstuff*/}}。每个函数的key就是选择的函数名,所以我需要得到它。
  • 好吧,如果您出于某种原因需要该名称,这是一个很好的做法。但它在 IE 中不起作用。但是你不能像@hindmost 建议的那样返回实际的函数,然后调用它吗?
猜你喜欢
  • 2021-11-17
  • 2018-02-08
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2016-08-27
  • 2021-08-20
相关资源
最近更新 更多