分享

Static variables in Javascript

 moonboat 2008-09-30

Static variables in Javascript

Static variables are variables, typically used in functions, that maintain their value between function calls. Javascript does not support static variables per se; their is no static keyword in the language. However in javascript all functions are also objects and we can use this fact to simulate static variables. All we have to do is create a variable that is a member of the function, and since it‘s now part of an object, the value will be retained between calls. While there aren‘t truly static in the strictest sense of the word, they maintain their value between functions calls, and that usually serves the purpose.

As an example, consider a completely lame, but very instructive, function that keeps track of the number of times that it has been called. Here‘s how it might look:

function countMyself() {
// Check to see if the counter has been initialized
if ( typeof countMyself.counter == ‘undefined‘ ) {
// It has not... perform the initilization
countMyself.counter = 0;
}
// Do something stupid to indicate the value
alert(++countMyself.counter);
}
 
function countMyself() {
 this.a;
 if(this.a == null){
  this.a = 0;
 }
 alert(++this.a);

}

Each time that the countMyself function gets called from the page, the value is shown increasing by one. Using this trick, you can easily simulate static variables in Javascript.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多