Building your own "VM" could be a pretty heavy lift.
Just treat any code you didn't write as part of an external application. Execute the script off-page, ideally in a sandbox on the server. (Use a spidermonkey plugin or a node sandbox.) At the very least, execute untrusted scripts in a frame on a totally separate domain.