Static variables in JavaScript

Just to make this clear there is no static variable in the sence of which C#,Java or C/C++ (just to name a few..) offers, but there is a “workaround”. First thing to do is to define a function:


funciton gnabber() {
// Make sure variable is/was initialized
if(typeof gnabber.counter == 'undefined' ) {
gnabber.counter = 0;
}

// Increment and return the "static" variable
gnabber.counter++;
return counter;
}

Now if you call the function i.e.:


gnabber(); // returns 1
gnabber(); // returns 2
gnabber(); // returns 3

The return value will always be one higher. If you want to start the index from 0 you have to put the increment part into an else block:


funciton gnabber() {
// Make sure variable is/was initialized
if(typeof gnabber.counter == 'undefined' ) {
gnabber.counter = 0;
} else {
// If variable already was initialized increment it
gnabber.counter++;
}

return counter;
}

This will result in:


gnabber(); // returns 0
gnabber(); // returns 1
gnabber(); // returns 2

The main thing you are using here is the ability to extend an object in JavaScript, use this where ever you need a static variable with some logic instead of a global variable.

Advertisements

Replacing Notepad with Notepad2 on Windows 7 64-bit

Late to the show but here I am, using notepad2 as my default notepad editor. I like the additions that notepad2 gives me over notepad and thereby delivering an equal snappy feeling when I open up a file with it. But replacing it as my default notepad on my Windows 7 64 Bit version took me more time than I am willing to admit.. So I thought I might well jot my solution down. I took my instructions from the notepad2 official webpage and Simon Steeles description on how to install his Programmer’s Notepad on a 64-bit Windows machine.First of all download a x64 version of the notepad2 then drag the folder into your program folder (on my machine C:\Program Files (x86)\notepad2). Now create a batch file (due to permissions you may want to first store it on your desktop and then drag it into the folder..):

reg add “HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe” /v “Debugger” /t REG_SZ /d “\”%~dp0Notepad2.exe\” /z” /f

Run the batch file (as Administrator) in your notepad2 directory. Now notepad2 should be your default editor.To reverse the step above run this batch script (again as Administrator):

reg delete “HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe” /f

Hello world!

After so many shout outs to us developers to get more social and share our experiences that we endeavor jobs, I want to do just that with this blog. Sharing my experience and views that I encounter and hope to help the one or other who might stumble over equal problems as me.