javascript - 如何判断哪个键调用了javascript中的函数
问题描述
如果我有一个具有多个键调用相同函数的对象,并且该函数在其范围之外实现,如何确定哪个键调用了该函数?例如:
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
对象。现在你要做的是在对象中查找被调用的函数实例,你就完成了。
推荐阅读
- postgres-9.6 - 防止在特定表 postgres 9.6 上进行 autovacuum
- gradle - Gradle 4.8+ 使用自定义配置打破了 ivy 发布
- python - 在 Tensorflow 中更改新分配变量的形状
- cypress - 赛普拉斯识别多个选项文本
- java - 从 Java 1.8 中的 HashMap 的 HashMap 中检索
- pkcs#11 - 使用 sunPKCS11 提供程序生成密钥对时的 CKR_USER_NOT_LOGGED_IN
- angular - 如何在 NG-ZORRO (Ant design) 表中实现排序器和过滤器
- java - Immutables 和 Hibernate vladmihalcea jsonb 类型的反序列化异常
- json - 我需要在 couchbase 中的 json 对象中添加一个键。我该如何为此编写查询?
- redux - 拆分 reducer 在 redux 中对同一片数据进行操作