Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 604
Mahdi Jaber Avatar asked May 21 '19 15:05

Mahdi Jaber


People also ask

How do you check if it's a function JavaScript?

Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.

What is a key in JavaScript?

JavaScript objects are comprised of properties. Properties in JavaScript are defined as pairs of keys and values. Keys can be generally thought of as the names of the values stored within JavaScript objects.

How do you check if an object is a function?

Use the typeof operator to check if an object contains a function, e.g. typeof obj. sum === 'function' . The typeof operator returns a string that indicates the type of the value. For functions, the operator returns a string containing the word function.


1 Answers

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.

like image 180
Serge Seredenko Avatar answered Sep 22 '22 02:09

Serge Seredenko