每次调用 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 传递给函数可能会更好。