如何在Javascript中创建静态变量?
当前回答
在使用jQuery的MVC网站中,我希望确保某些事件处理程序中的AJAX操作只能在前一个请求完成后执行。我使用一个“静态”jqXHR对象变量来实现这一点。
按下以下按钮:
<button type="button" onclick="ajaxAction(this, { url: '/SomeController/SomeAction' })">Action!</button>
我通常使用这样的IIFE作为点击处理程序:
var ajaxAction = (function (jqXHR) {
return function (sender, args) {
if (!jqXHR || jqXHR.readyState == 0 || jqXHR.readyState == 4) {
jqXHR = $.ajax({
url: args.url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify($(sender).closest('form').serialize()),
success: function (data) {
// Do something here with the data.
}
});
}
};
})(null);
其他回答
摘要:
在ES6/ES 2015中,class关键字与附带的静态关键字一起引入。请记住,这是javavscript所体现的原型继承模型的语法糖。static关键字对方法的工作方式如下:
类狗{静态树皮(){console.log('wof');}//类是隐藏的函数对象//树皮方法位于Dog函数对象上makeSound(){console.log('bark');}//makeSound位于Dog.prototype对象上}//要创建静态变量,只需在类的原型上创建一个属性Dog.prototype.breed=“Pitbull”;//因此,要定义静态属性,我们不需要“static”关键字。const蓬松=新狗();const vicky=新狗();控制台.日志(绒毛.品种,vicky.品种);//更改静态变量会更改所有对象上的静态变量Dog.prototype.breed=“梗”;控制台.日志(绒毛.品种,vicky.品种);
如果您正在使用新的类语法,那么现在可以执行以下操作:
类MyClass{静态获取myStaticVariable(){返回“一些静态变量”;}}console.log(MyClass.myStaticVariable);aMyClass=新建MyClass();console.log(aMyClass.myStaticVariable,“未定义”);
这有效地在JavaScript中创建了一个静态变量。
除其他内容外,目前还有一个关于ECMA提案的草案(第2阶段提案),它在类中引入了静态公共字段。(考虑了私人领域)
使用提案中的示例,建议的静态语法如下所示:
class CustomDate {
// ...
static epoch = new CustomDate(0);
}
并等同于其他人强调的以下内容:
class CustomDate {
// ...
}
CustomDate.epoch = new CustomDate(0);
然后,您可以通过CustomDate.epoch访问它。
您可以在提案静态类特性中跟踪新提案。
目前,babel通过您可以使用的转换类财产插件支持此功能。此外,尽管仍在进行中,V8正在实现它。
可以在声明静态变量后重新分配函数
function IHaveBeenCalled() {
console.log("YOU SHOULD ONLY SEE THIS ONCE");
return "Hello World: "
}
function testableFunction(...args) {
testableFunction=inner //reassign the function
const prepend=IHaveBeenCalled()
return inner(...args) //pass all arguments the 1st time
function inner(num) {
console.log(prepend + num);
}
}
testableFunction(2) // Hello World: 2
testableFunction(5) // Hello World: 5
这使用。。。args比较慢,有没有办法第一次使用父函数的作用域而不是传递所有参数?
我的用例:
function copyToClipboard(...args) {
copyToClipboard = inner //reassign the function
const child_process = require('child_process')
return inner(...args) //pass all arguments the 1st time
function inner(content_for_the_clipboard) {
child_process.spawn('clip').stdin.end(content_for_the_clipboard)
}
}
如果要在作用域之外使用child_process,可以将其分配给copyToCclipboard的属性
function copyToClipboard(...args) {
copyToClipboard = inner //reassign the function
copyToClipboard.child_process = require('child_process')
return inner(...args) //pass all arguments the 1st time
function inner(content_for_the_clipboard) {
copyToClipboard.child_process.spawn('clip').stdin.end(content_for_the_clipboard)
}
}
您可以利用JS函数也是对象这一事实,这意味着它们可以具有财产。
例如,引用Javascript中静态变量一文(现已消失)中给出的示例:
function countMyself() {
// Check to see if the counter has been initialized
if ( typeof countMyself.counter == 'undefined' ) {
// It has not... perform the initialization
countMyself.counter = 0;
}
// Do something stupid to indicate the value
alert(++countMyself.counter);
}
如果多次调用该函数,您将看到计数器正在递增。
这可能是一个比用全局变量替换全局命名空间更好的解决方案。
下面是基于闭包的另一种可能的解决方案:在javascript中使用静态变量的技巧:
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.
这会得到相同的结果——只是这次返回的是递增的值,而不是显示。