I was perusing the source code for Dean Edwards’ base2 library when I discovered that functions can access the parameters of other functions in the call stack. My mind immediately started spinning, imagining the convoluted code this would allow.
Here’s one to get you started:
function checkArgTypes(/*expected types*/) {
var callerArgs = arguments.callee.caller;
if (callerArgs.length !== arguments.length) {
throw new Error('checkArgTypes does not have enough arguments.');
}
for (var i = 0; i < arguments.length; i++) {
if (typeof callerArgs[i] !== arguments[i]) {
throw new Error('Argument ' + (i+1) + ' is of type ' + typeof callerArgs[i] + ' but should be of type ' + arguments[i] + '.');
}
}
}
function run(str, num, bool) {
checkArgTypes('string', 'number', 'boolean');
}
You might want to try it out in jconsole.
And, of course, you can’t ignore the obligatory security implications:
function validateUser(username, password) {
/* accidentally call trojan function */
trojan();
}
function trojan() {
alert('Your password is ' + validateUser[1] + '.');
}
validateUser('user', 'secret');
Ahh, well. I’d best get back to writing real code.
NOTE: Edited to fix WordPress source code formatting problem.
Update: Fixed a typo in my “for” loop. (Thanks Philippe!)
Hi Matthias
Thank you for sharing this.
Though, I realize you make one more loop with the <= comparison in your for loop.
Cheers!
Comment by Philippe Rathe — December 13, 2007 @ 6:48 pm
in second snippet:
shouldn’t it be validateUser.arguments[1] ?!
regards
Comment by Friedemann Altrock — February 28, 2008 @ 10:55 pm
If you have trojan Javascript replacing functions called by your validateUser function you’re already screwed, since trojan code can just as easily replace validateUser itself. So there isn’t really a security issue here.
Comment by Mr. Shiny & New — August 19, 2008 @ 7:01 pm