如何跟踪 JavaScript 方法中的先前值?
我需要将方法中的当前整数与先前的整数进行比较。看起来这样的事情应该有效,但事实并非如此。有人能告诉我问题出在哪里吗?请注意,电流是在方法外部设置的。
myMethod : function() {
var previous;
if ( current > previous ) {
// do this!
}
previous = current;
}
I need to compare a current integer with a previous integar within a method. It seems like something like this should work, but it doesn't. Can someone tell me where the problem lies? Note current is set outside the method.
myMethod : function() {
var previous;
if ( current > previous ) {
// do this!
}
previous = current;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎您正在尝试实现记忆功能。有一个关于如何进行操作的很好的教程 这里。
Seems like you are trying to implement a memoization function. There is a good tutorial on how to go about it here.
每次调用
myMethod
时,都会重新声明previous
(var previous
)。您有四种可能性:
(A)创建一个闭包(在我看来是最好的解决方案,但取决于您的需求):(
B)将
previous
设置为函数对象的属性:但这将函数与对象的命名。
(C) 如果它适合您的模型,则将
previous
设为对象的属性myMethod
是以下属性的属性:(D) 与 (A) 类似,设置
previous
更高范围之外的某个地方:在我看来,这不是一个好主意,因为它污染了更高范围。
如果没有看到更多代码,很难判断,但是当您将
current
传递给函数时,情况可能会更好。Every time you call
myMethod
,previous
is declared anew (var previous
).You have four possibilities:
(A) Create a closure (best solution imo, but depends on your needs):
(B) Set
previous
as property of the function object:But this ties the function very much to the naming of the object.
(C) If it fits in your model, make
previous
a property of the objectmyMethod
is a property of:(D) Similar to (A), set
previous
somewhere outside in a higher scope:This is not a good imo as it pollutes the higher scope.
Without seeing more of your code it is hard to tell, but it is probably also better when you pass
current
to the function.你只需要保持状态。
You just need to maintain state.