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!)




