No, you can't do this. You can't inject code into arbitrary functions and mess around with their local scope by changing the Function.prototype, and that's a good thing.
Besides, how would you enforce using the local object for local variables anyway? And how would you allow variable lookups through parent scopes, such as in:
function f() {
var a = 5;
return function g(b) {
return a + b;
};
}
In your solution, you'd have a local object in the f and g functions, but the local variable in g would hide the parent's variable...
function f() {
var local = { a : 5 };
return function g(b) {
// This declaration hides the parent's declaration
var local = { b : b };
// How would local.a be found?
return local.a + local.b;
};
}
There's a much simpler solution to your original problem though: just enable strict mode with "use strict". That way, you get an error when you accidentally leak a variable into the global scope. For example, your second sample would throw a ReferenceError when it tries to access the undeclared i variable (instead of creating a new global variable).
Do note that strict mode goes further than just preventing accidental global variables, read up on it so you understand the consequences!
"use strict"? That way, you get an error when you accidentally leak a variable into the global scope.varkeyword.varkeyword). Usingvaris much more readable and "standard".