Saturday, 26 August 2017

Javascript, using one single local object instead of many local variables

I often use jslint and tools to verify my code for programming errors, etc...



During the course of my programming I often find that I need a local variable or a local function to do some simple things. So I go to my main single var statement at the top of my local scope and adjust it, sometimes breaking my creative flow. So sometimes instead I declare a single line var in the middle of my code to continue my programming and then move it at the top var statement during refactoring afterwards.



I had an idea today that i want to explore and did not find anything on it on Google or stackoverflow.



My idea is this, just declare a single temp object and use it for whatever the need. Ex: adding some attribute for a new variable or function.



So instead of :




// if I omit the last comma, the next variable will be a global
var variable1 = "Hello World!",
variable2 = "Testing...";

(... some code ...)
var variable3 = 42;


I would instead use :




var temp = {};
temp.variable1 = "Hello World!";
temp.variable2 = "Testing...";

(... some code ...)
temp.variable3 = 42;


So I do not risk polluting the global namespace, I declare variable as needed and do not struggle with that var statement since I always know that a variable preceded by "temp." is in the local scope.




Any comment or advice will be appreciated.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...