打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Static variables in Javascript

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 initializedif ( typeof countMyself.counter == ‘undefined‘ ) {// It has not... perform the initilizationcountMyself.counter = 0;}// Do something stupid to indicate the valuealert(++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.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
What is the Execution Context & Stack in JavaScript? by David Shariff
Writing Reentrant and Thread-Safe Code
Function Calling Convention(基于栈的函数调用惯例)
用 Javascript 封装了一个HashMap
echarts 树图tree 改为流程图
一个用 JavaScript 实现的简陋的计算器:
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服