I try to refrain from determining morality associated with code, but I'm thinking this example may have to transcend that to being truly evil.

var myfunc2 = function () {
    alert("I don't exist");
};

function myfunc () {
    with (this) {
        eval("myfunc2 = function () " +
             "{ alert(\"Hey I exist.\"); }; ");
    }
}

myfunc();
myfunc2();

I love the flexible nature of Javascript's objects, it makes it fun to program in. But combining this, eval and with is where things start to get scary. The funny part is that I made this example because I want to use this feature.

For those who aren't really familiar with Javascript this is overriding the traditional lexical scoping by using a with to make the global object the current object. this is the global object on functions that are declared in the global object. So, effectively we can create functions that are usable elsewhere from strings even through we're in a function. Useful, but definitely hard to read.


posted Nov 16, 2006 | permanent link