How to tell which key called a function in javascript
It is possible
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
}
Explanation: arguments.callee
is reference to the function to which the arguments
object belongs. And this
is basically "a thing before the dot" at the moment of function invocation, therefore your Population
object. Now what you do is lookup the called function instance in the object and you are done.
function tellYourAge() {
return function()
{
var s = new Error().stack;
if(s.includes('Mahdi')){
console.log('Age is 18');
}
else if(s.includes('Samuel')){
console.log('Age is 20');
}
else if(s.includes('Jon')){
console.log('Age is 21');
}
}
}
{
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
}
Output:
Age is 18
Age is 20
Age is 21
FYI, new Error().stack will give you stacktrace like below,
Error
at Object.Samuel (<anonymous>:4:20)
at <anonymous>:1:19