我需要在一个方法中将当前整数与之前的整数进行比较。看起来像这样的东西应该工作,但事实并非如此。有人可以告诉我问题出在哪里吗?注意当前是在方法之外设置的。
myMethod : function() {
var previous;
if ( current > previous ) {
// do this!
}
previous = current;
}
最佳答案
每次调用 myMethod
时,都会重新声明 previous
(var previous
)。
你有四种可能:
(A) 创建闭包(我认为是最佳解决方案,但取决于您的需要):
myMethod : (function() {
var previous = null;
return function() {
if ( current > previous ) {
// do this!
}
previous = current;
}
}());
(B) 将previous
设置为函数对象的属性:
myMethod : function() {
if ( current > foo.myMethod.previous ) {
// do this!
}
foo.myMethod.previous = current;
}
foo.myMethod.previous = null;
但这将功能与对象的命名紧密联系在一起。
(C) 如果它适合您的模型,请将 previous
设为对象的属性 myMethod
是以下对象的属性:
previous: null,
myMethod : function() {
if ( current > this.previous ) {
// do this!
}
this.previous = current;
}
(D) 与(A) 类似,将previous
设置在更高范围之外的某处:
var previous = null;
// ...
myMethod : function() {
if ( current > previous ) {
// do this!
}
previous = current;
}
这不是一个好的 imo,因为它会污染更高的范围。
如果不查看更多代码,很难判断,但将 current
传递给函数时可能会更好。
关于javascript - 如何跟踪 JavaScript 方法中的先前值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5885999/