I have functions in JavaScript that need to verify if they are being called by the correct function (for example, it requires the function
something.stuff.morestuff.coolFunction
to initiate it). I attempted using Function.caller
, but it only gives me the function itself without any information on its containing objects.
Consider the following scenario:
function helloWorld(){
if(/* exact path of calling function */ === 'greetings.happy.classic.sayhello'){
console.log('Hello World');
}else{
console.log(/* previous path */ + ' not permitted.');
}
}
greetings = {
happy: {
classic: {
sayHello: function(){ helloWorld(); },
sayBye: function(){ helloWorld(); }
}
},
angry: {
sayHello: function(){ helloWorld(); }
},
simple: [
function(){ helloWorld(); }
]
}
function sayWords(){
helloWorld();
}
Desired output:
greetings.happy.classic.sayHello(); // => Hello World!
greetings.happy.classic.sayBye(); // => greetings.happy.classic.sayBye not allowed.
greetings.angry.sayHello(); // => greetings.angry.sayHello not allowed.
greetings.simple[0](); // => greetings.simple[0] not allowed.
sayWords(); // => sayWords not allowed.
helloWorld(); // => null not allowed.
// unsure what would be returned here, so used null
The main question is:
How can I determine the complete object path (e.g.,
greeting.happy.classic.sayHello
) of the calling function?Function.caller.name
only gives the function name, which is insufficient. The entire hierarchy of the calling function's location is needed.
This seems like a complex issue, so thank you all for your assistance.