Have javascript declare by default undeclared variables to the current local scope based on first use instead of global scope

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Can this be done either via writing some code to intercept the global scope default declaration or via a setting within the javascript engine itself which each program or function has access to?

What I mean is if I could, at the top of the program (or function), tell the javascript engine to use local scope for undeclared variables instead of global scope... then, when the javascript engine compiles each function, it would declare them in local scope.

I understand if you want to declare a variable outside of the current scope, that should be done explicitly since no one knows where you want it declared, but I think defaulting to global scope leaves too much room for error and forces too much typing of var statements in each function, so I d like to change the default in my programs if that s possible.

My primary purpose is to avoid having to type the list of local variables in a var statement at the top of every function, and to avoid the maintenance of keeping this list in sync with the local variables as I m using them within a function. Not allowing a global scope default also reduces the risk of errors.

I would never want undeclared variables to end up in any higher scope than the scope in which they are first used. There is no value in having them default to global scope that I can see.

I know I can explicity declare variables in the current scope (or the global scope), but would like to avoid doing so and use a more useful default than the global scope default built into javascript.

I also know I can use "use strict" to force all variables to be declared explicitly. Not wanting to debate the right or wrong of it, but just asking if there is any way to change the default to local scope instead of global scope for a given function.

Answers

No, Javascript behaves the way it does, there s no switch to flip to turn its variable declaration rules on its head.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Converting_mistakes_into_errors https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Converting_mistakes_into_errors

http://coffeescript.org/#lexical-scope http://coffeescript.org/#lexical-scope

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/27893143/have-javascript-declare-by-default-undeclared-variables-to-the-current-local-s

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils