javascript - 如何判断哪个键在javascript中调用了一个函数

标签 javascript function object

如果我有一个具有多个键调用同一个函数的对象,并且这个函数是在它的范围之外实现的,如何确定哪个键调用了这个函数?例如:

function tellYourAge() {
   return function()
   {
       // I already know here that this refers to Population
       // For example, console.log(this) will print the Population object
   }
}

{
   let Population = {
     Mahdi: tellYourAge(),
     Samuel: tellYourAge(),
     Jon: tellYourAge()
   };

   Population.Mahdi(); // It should log 18
   Population.Samuel(); // It should log 20
   Population.Jon(); // It should log 21
}

最佳答案

有可能

function tellYourAge() {
   return function()
   {
       var f = arguments.callee;
       var key = Object.keys(this).filter(key => this[key] === f)[0];
       console.log(key);
   }
}

{
   let Population = {
     Mahdi: tellYourAge(),
     Samuel: tellYourAge(),
     Jon: tellYourAge()
   };

   Population.Mahdi(); // prints Mahdi
   Population.Samuel(); // prints Samuel
   Population.Jon(); // prints Jon
}

说明:arguments.callee 是对arguments 对象所属函数的引用。并且 this 在函数调用时基本上是“点之前的东西”,因此是您的 Population 对象。现在你要做的是在对象中查找被调用的函数实例,你就完成了。

关于javascript - 如何判断哪个键在javascript中调用了一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241807/

相关文章:

javascript - window.matchMedia(mediaQueryString) 是否接受 mediaQueryString 变量?

python - "Variable"未访问

java - 打印数组中对象的单个元素。 java

function - 如何更正 "Function definitions are not permitted at the prompt or in scripts"

javascript - 有没有办法使用数字类型作为对象键?

JavaScript:在数组中查找具有数组子字符串的所有值

javascript - 防止 react-redux 在状态改变时重新渲染整个页面

javascript - 无法使用 Ajax 将数据列表从 Controller 返回到 View 中的下拉列表。我收到未定义的未定义错误

javascript - 为什么要在函数定义调用对中编写全局代码?

javascript - 如何更改 opentok javascript SDK 中的音频输出?