简体   繁体   中英

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'.

I do not want to pass any parameter to the getMenu and calling arguments.callee.name will always return getMenu . Is there another way to get the name calling the getMenu function?

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. 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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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