I have functions in JavaScript that need to check that the function running it is, indeed, the correct function (ex, needs the function something.stuff.morestuff.coolFunction
to have called it or it wont run).
I've tried getting Function.caller
, but this only returns the function itself, and no way to determine which objects it is inside of.
Given the following setup:
function helloWorld(){
if(/* the exact path to the calling function */ === 'greetings.happy.classic.sayhello'){
console.log('Hello World');
}else{
console.log(/* the path from earlier */ + ' not allowed.');
}
}
greetings = {
happy: {
classic: {
sayHello: function(){ helloWorld(); }
sayBye: function(){ helloWorld(); }
}
},
angry: {
sayHello: function(){ helloWorld(); }
},
simple: [
function(){ helloWorld(); }
]
}
function sayWords(){
helloWorld();
}
What I'm trying to accomplish would look like this:
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.
// not sure what would come out of this, so i put null on that one
Here's the question in one neat little package:
How would I find the exact object path (i.e.
greeting.happy.classic.sayHello
) of the calling function?Function.caller.name
just returns the name of the function, which is not enough. I need the full tree of the calling function's location.
This feels like a complex issue, so thank all for your help.