【发布时间】:2019-10-08 01:20:24
【问题描述】:
如果我有一个具有多个键调用同一个函数的对象,并且该函数在其范围之外实现,如何确定哪个键调用了该函数?例如:
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
}
【问题讨论】:
-
将密钥作为参数传递,例如:
Mahdi: tellYourAge('Mahdi') -
那些已经是独立的函数了。
-
I want to do it without passing a parameter为什么? -
没有从键到值的链接。您要么必须通过它,要么必须重新考虑它的设置方式。
-
您无法完全按照描述的方式实现此目的。您可以使用块范围或 Function.prototype.bind 来做一些事情。
标签: javascript function object