I'm currently researching a way to protect JavaScript functions as private, exception will be thrown if the caller is invalid. Then I have a problem here: If a closure is defined inside a valid caller, is it a way to get the valid caller from the inner closure?
For example:
function validCaller() {
var self = this;
self.privateFunction1();
$.each([/*...*/], function (key, val) {
self.privateFunction2();
});
}
And, of course, privateFunction1
will get the caller validCaller
correctly, but privateFunction2
will get the anonymous function as caller, so the access will be denied.
It is not the right way if I get validCaller from the call stack by expression caller.caller.caller
, because I can't determine how many levels should I trace back, and, in some special cases, the anonymous function needs to be called outside of validCaller
.
Maybe I asked the question in a complicated way, the simple way is:
how can I capture a function's scope chain?