I've gotten into the habit of adding the following at the top of all my functions:
var local = {};
That way, I explicitly scope all my variables. For example:
for (local.i=0; local.i<x; local.i++) {} // local scope: good!
for (i=0; i<x; i++) {} // accidental global scope: bad!
Q: Is there a way to change the Function prototype to include var local={}; as part of it's definition? That way I can assume that "local." means explicitly in the local scope.
The answer is no, you can't implicitly add a variable declaration and initialize it in every function scope (thank goodness). You need to manage your variable scopes manually, employing analysis tools when/if desired.
Imagine for a moment if this was possible. Any code you load could potentially corrupt any other variable scope, effectively defeating the purpose of scoped variables.
The Function.prototype
will not help because prototypal inheritance has nothing to do with variable scope.
Your trick to protect i
by putting it in a local
object doesn't solve anything. It just moves the problem from the i
variable to the local
variable, and still doesn't keep you from using i
instead of local.i
.
While including "use strict";
can help by providing helpful error messages, you need to keep in mind that it changes behavior in some situations that can break code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With