Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a local scope to functions

Tags:

javascript

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.

like image 732
Phillip Senn Avatar asked Oct 02 '22 01:10

Phillip Senn


1 Answers

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.

like image 159
cookie monster Avatar answered Oct 13 '22 10:10

cookie monster