Sunday, 9 June 2019

How to tell which key called a function in javascript

If I have an object with multiple keys calling the same function and this function is implemented outside its scope, how to determine which key called this function? For example:

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
}



from How to tell which key called a function in javascript

No comments:

Post a Comment