Thursday, July 3, 2008

Trick to use static variables in javascript

Maybe people that have background in C language know how to do this because in C language there is a static keyword to declare a static variable. What is about Javascript?

Well, Javascript doesn't have static keyword. One way to solve this problem, you may use global variable. However, for some people, it will pollute the global namespace. Last night, I read a javascript book, Javascript - The Definitive Guide, 5th edition. The author used closure to achieve this by returning back the anonymous function.


var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.



uniqueID(); // 0

uniqueID(); // 1

uniqueID(); // 2

29 comments:

Anonymous said...

with({n:0})var id=function(){return n++;};

chamnap said...

great, thanks

George Garchagudashvili said...

good job really :)

Anonymous said...

Genial brief and this fill someone in on helped me alot in my college assignement. Say thank you you on your information.

Anonymous said...

i very love your writing choice, very unique.
don't give up and also keep creating in all honesty , because it just simply nicely to follow it,
impatient to looked over additional of your own web content, have a good day!

Edu said...

This is good. The problem is if you put that static var inside a simulated object.

function test(){
//your code (suppose static_var)
}

var test1 = new test();
var test2 = new test();

Your code doest work here, because we have two different "objects".

Do you know a way to do this?

Thanks

Edu said...

If you want to do that (i've found out now):

is a lot of code for a static variable but:

function FormEl(options){
if(typeof FormEl.n_objects == 'undefined')
FormEl.n_objects=0;
FormEl.n_objects++;
var n_objects = FormEl.n_objects;

alert("One More");
alert(n_objects);
}

var o1 = new FormEl();
var o2 = new FormEl();

chamnap said...

Edu: Your solution is fine, but it adds a public property "n_objects" to FormEl object.

Anonymous said...

var Foo = (function() {

// number times instantiated
var instances = 0

return function() {

// unique instance number
var _instance = ++instances;

// get object instance number
this.getInstanceNum = function() {
return _instance;
};

};

})();

var foo1 = new Foo();
var foo2 = new Foo();
var foo3 = new Foo();

alert(foo1.getInstanceNum());
alert(foo2.getInstanceNum());
alert(foo3.getInstanceNum());

alert(foo1.getInstanceNum());
alert(foo2.getInstanceNum());
alert(foo3.getInstanceNum());

chamnap said...

Yes, that's fine too. You use singleton pattern in javascript.

Curvve said...

A good website design is very important for any business. It is advised to not design heavy sites .now a days website design growth is extreme level but how effective that website.

Secure Web Design

Anonymous said...

ambien internet order where can you buy ambien over the counter - purchase ambien online canada

Anonymous said...

purchase ambien overnight delivery where to buy ambien cr in canada - where to buy ambien in mexico

Anonymous said...

Super Awesome Technique..
Thanks a lot for sharing.

Anonymous said...

App Development Company should be able of doing a complete web development and web design activities. There are some companies which will offer only front end designing by using web designers and some of them will have only web developers who will code the back end with high quality but they will have very little knowledge in front end designing. So, always find a company where there will be both designers and developers which will be helpful in developing the complete website in at place.

Cado Magenge
" web development company melbourne | mobile apps development companies melbourne
website development company melbourne | magento development company "

Claudia D said...

Hi,

Very good solution! I am new to javascript and I want to send a parameter in order to start from another number dinamically.
For example I want to call uniqueId(3) and in the function the id should start from 3. How would the function would look like?

Unknown said...

Thanks for the post.It helped me a lot.Thanks!!!!!!Keep the good work up!
SEO Experts India
SEO Experts India
SEO Experts in Bangalore

5689 said...

zzzzz2018.9.6
dsquared2
off white clothing
reebok outlet
red bottom shoes
christian louboutin outlet
champion clothing
jordans
off white shoes
christian louboutin
ugg boots

Unknown said...

www1129
ray ban sunglasses
hugo boss
ralph lauren polo
michael kors outlet
coach outlet
prada handbags
coach outlet
michael kors outlet
moncler outlet
nike blazers

Chiến SEOCAM said...

Very excellent, an excellent article. Thank you

chó Bull Pháp

bán chó bull pháp

chó bull pháp giá bao nhiêu

mua chó bull pháp

Anonymous said...

https://flipboard.com/@jay57ms/tips-mudah-menemukan-situs-judi-online-yang-terpercaya-3q021f9sy
https://sparklewpthemes.com/support/users/wilz1701/
https://wilzryuzakii.kinja.com/lebih-untung-mainkan-judi-via-situs-judi-online-1839604696?rev=1572876726828
https://medium.com/@pokerwowww/keuntungan-yang-bisa-anda-dapat-saat-bermain-slot-online-84f85ac84739
https://www.wordnik.com/users/wilz17
https://id.techinasia.com/author/rezekiforum
https://www.couchsurfing.com/people/nagapoker
https://www.emailmeform.com/builder/form/84X1Ld70fh7DE3
https://form.jotform.me/93093973594472
https://www.jssor.com/wilz1701/pokerwow.slider

yanmaneee said...

yeezy boost 500
off white shoes
jordan sneakers
yeezy boost 350
golden goose sneakers
balenciaga shoes
off white jordan 1
yeezy boost 350 v2
balenciaga sneakers
kyrie 5 spongebob

erectile dysfunction medications said...

I am really enjoying the theme/design of your web site. Do you ever run into any internet browser compatibility problems? A handful of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Safari. Do you have any ideas to help fix this issue?

Amit Gupta said...

Blog is too interesting and suggested also the web development and Social media marketing services Delhi in full descriptive way.

toose said...

he has a good point Ysl replica handbags blog link luxury replica bags More Info high end replica bags

neighneet said...

replica bags from turkey replica gucci bags e1f79o6t91 replica bags wholesale in divisoria my latest blog post o7c47y7x68 Ysl replica bags replica bags turkey replica bags in bangkok replica hermes bags y4q98j9x83 replica bags online pakistan

Anonymous said...

off white shoes
yeezy shoes
supreme t shirt
yeezy boost 350
fear of god outlet

Tracy David said...
This comment has been removed by the author.
Rony jim said...

Thankyou for the informative post, Great One!
Traffic Lawyer Edmonton

Subscribe in a Reader