Out of Hanwell

October 17, 2007

Don’t Steal My Parameters

Filed under: Humor/Mental Leisure, JavaScript — Matthias Miller @ 1:33 pm

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&#91;i&#93; !== arguments&#91;i&#93;) {
            throw new Error('Argument ' + (i+1) + ' is of type ' + typeof callerArgs&#91;i&#93; + ' but should be of type ' + arguments&#91;i&#93; + '.');
        }
    }
}

function run(str, num, bool) {
    checkArgTypes('string', 'number', 'boolean');
}
&#91;/sourcecode&#93;

You might want to try it out in <a href="http://www.jconsole.com/">jconsole</a>.

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

Advertisements

October 5, 2007

Python: A Gateway to Understanding JavaScript

Filed under: JavaScript — Matthias Miller @ 3:46 pm

The past day or two I’ve been exploring Python. Although I’ve enjoyed tinkering with the language, I’ve never done any serious development with it. As I explored it more, I was surprised to find that Python’s approach to object-oriented programming provides a great foundation for understanding JavaScript’s objects and prototype chains. The two languages are conceptually similar, but Python provides object-orientation in a much cleaner, straightforward way.*

In my opinion, someone should write a tutorial that first introduces the concepts of object-oriented Python, then illustrates how the same concepts apply to JavaScript.

* To defend myself against JavaScript purists, the point is to better understand JavaScript as a language. It’s not that I’m trying to coerce JavaScript into the mold of another language.

Blog at WordPress.com.