如何在Javascript中创建静态变量?
当前回答
JavaScript中最接近静态变量的是一个全局变量——这只是一个在函数或对象文本范围之外声明的变量:
var thisIsGlobal = 1;
function foo() {
var thisIsNot = 2;
}
您可以做的另一件事是将全局变量存储在对象文本中,如下所示:
var foo = { bar : 1 }
然后像这样访问变量:foo.bar。
其他回答
ES6类支持静态函数,其行为与其他面向对象语言中的静态函数非常相似:
class MyClass {
static myFunction() {
return 42;
}
}
typeof MyClass.myFunction; // 'function'
MyClass.myFunction(); // 42
通用静态财产仍然是第三阶段的建议,这意味着您需要巴贝尔的第三阶段预设才能使用它们。但有了Babel,你可以做到这一点:
class MyClass {
static answer = 42;
}
MyClass.answer; // 42
还有另一种方法,它解决了我浏览这个线程后的需求。这完全取决于您想要使用“静态变量”实现什么。
全局属性sessionStorage或localStorage允许在会话的生命周期内存储数据,或在明确清除之前存储不确定的更长时间。这允许在页面/应用程序的所有窗口、框架、选项卡面板、弹出窗口等之间共享数据,并且比一个代码段中的简单“静态/全局变量”功能强大得多。
它避免了顶级全局变量(如Window.myglobal)的范围、生存期、语义、动态等方面的所有麻烦。不知道它有多高效,但这对于以适度速度访问的少量数据来说并不重要。
轻松访问为“sessionStorage.mydata=anything”,并以类似方式检索。看见“JavaScript:最终指南,第六版”,David Flanagan,ISBN:978-0-596-80552-4,第20章,第20.1节。通过简单的搜索,或在O’Reilly Safaribooks订阅(价值黄金)中,可以轻松下载为PDF格式。
您可以使用static关键字在JavaScript中定义静态函数:
class MyClass {
static myStaticFunction() {
return 42;
}
}
MyClass.myStaticFunction(); // 42
在撰写本文时,您仍然无法在类中定义静态财产(函数除外)。静态财产仍然是第三阶段的建议,这意味着它们还不是JavaScript的一部分。然而,没有什么可以阻止您像分配给任何其他对象一样简单地分配给类:
class MyClass {}
MyClass.myStaticProperty = 42;
MyClass.myStaticProperty; // 42
最后一点:小心使用带有继承的静态对象-所有继承的类共享对象的相同副本。
要在这里浓缩所有的类概念,请测试:
var Test = function() {
// "super private" variable, accessible only here in constructor. There are no real private variables
//if as 'private' we intend variables accessible only by the class that defines the member and NOT by child classes
var test_var = "super private";
//the only way to access the "super private" test_var is from here
this.privileged = function(){
console.log(test_var);
}();
Test.test_var = 'protected';//protected variable: accessible only form inherited methods (prototype) AND child/inherited classes
this.init();
};//end constructor
Test.test_var = "static";//static variable: accessible everywhere (I mean, even out of prototype, see domready below)
Test.prototype = {
init:function(){
console.log('in',Test.test_var);
}
};//end prototype/class
//for example:
$(document).ready(function() {
console.log('out',Test.test_var);
var Jake = function(){}
Jake.prototype = new Test();
Jake.prototype.test = function(){
console.log('jake', Test.test_var);
}
var jake = new Jake();
jake.test();//output: "protected"
});//end domready
好吧,另一种了解这些方面最佳实践的方法是看看咖啡脚本是如何翻译这些概念的。
#this is coffeescript
class Test
#static
@prop = "static"
#instance
constructor:(prop) ->
@prop = prop
console.log(@prop)
t = new Test('inst_prop');
console.log(Test.prop);
//this is how the above is translated in plain js by the CS compiler
Test = (function() {
Test.prop = "static";
function Test(prop) {
this.prop = prop;
console.log(this.prop);
}
return Test;
})();
t = new Test('inst_prop');
console.log(Test.prop);
我有通用方法:
创建对象,如:stat_flags={};将其用于动态添加字段:flags.popup_save_inited=true;下次询问对象中是否需要标记并执行逻辑
例子:
class ACTGeneratedPages {
constructor(table_data, html_table_id) {
this.flags = {};//static flags for any processes
//any your code here
}
call_popup(post_id) {
let _this = this;
document.getElementById('act-popup-template').style.display = 'block';
if (!this.flags.popup_save_inited) {//second time listener will not be attached
document.querySelector('.act-modal-save').addEventListener('click', function (e) {
//saving data code here
return false;
});
}
this.flags.popup_save_inited = true;//set flag here
}
}
推荐文章
- 右击是Javascript事件吗?
- 如何找到JavaScript数组中包含的最大数字?
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;