简体   繁体   English

如何使用父名称获取函数名称?

[英]How to get a function name using a parent name?

If I have object called menu: 如果我有称为菜单的对象:

var menu  ={
    pizza: getMenu,    
    burger: getMenu
}

function getMenu(){
    //do something
}

I want if I call menu.burger() to console.log 'burger' and doing menu.pizza() to log 'pizza'. 我想如果将menu.burger()调用为console.log ',并执行menu.pizza()来记录'pizza'。

I do not want to pass any parameter to the getMenu and calling arguments.callee.name will always return getMenu . 我不想将任何参数传递给getMenu并调用arguments.callee.name将始终返回getMenu Is there another way to get the name calling the getMenu function? 还有另一种方法来获取名称,调用getMenu函数吗?

There are several ways of achieving what you want. 有几种方法可以实现您想要的。 Either by using a non-enumerable tracker on the menu object, or modifying the functions a bit. 通过在菜单对象上使用不可枚举的跟踪器,或稍微修改功能。 I'll write here the simplest one: 我在这里写最简单的一个:

var menu  ={
    pizza: function(){getMenu.call(this,"pizza")},    
    burger: function(){getMenu.call(this,"burger")}
}

function getMenu(key){
    console.log(key);
}
menu.pizza();//pizza

If you want to achieve what you want without passing a parameter to getMenu, you would need to use another nonenumerable getter/setter to keep track of the last called method. 如果要在不将参数传递给getMenu的情况下实现所需的功能,则需要使用另一个无数的getter / setter来跟踪最后一个调用的方法。 Other ways can also achieve that, but if all you want is to console log, I'd use anonymous functions that are kept separately in memory so they are unique: 其他方法也可以实现这一点,但是如果您只想控制台日志,我将使用匿名函数,这些函数分别保存在内存中,因此它们是唯一的:

   var menu  ={
        pizza: function(){for(var i in this){if(this[i] === menu.pizza){console.log(i);break;}}},    
        burger: function(){for(var i in this){if(this[i] === menu.burger){console.log(i);break;}}}
    }
    menu.pizza()//pizza

wayyy simpler 更简单

Here is my solution, fine but not beautiful :D 这是我的解决方案,很好,但不是很漂亮:D

var menu = {
  pizza: getMenu,
  burger: getMenu
}

function getMenu() { console.log('do something') }


Object.keys(menu).forEach(item => {
  Object.defineProperty(menu, item, {
    configurable: true,
    enumerable: true,
    set(val){
      this.value=val
    },
    get() {
      console.log(item)
      return this.value
    }
  })
  menu[item] = getMenu
})


console.log(menu.pizza())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM