javascript - 如何跟踪 JavaScript 方法中的先前值?

标签 javascript variables methods

我需要在一个方法中将当前整数与之前的整数进行比较。看起来像这样的东西应该工作,但事实并非如此。有人可以告诉我问题出在哪里吗?注意当前是在方法之外设置的。

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/

相关文章:

Java:使用其他类的方法

javascript - 如何在 React Router 中将 props 传递给 <Link> ? React.js、JavaScript

javascript - 如何动态设置关联数组的命名索引?

javascript - 为什么这个递归 javascript 函数返回未定义?

javascript - 为什么 Button 组件在单击时改变位置?

python - 下划线 _ 作为 Python 中的变量名

c# - 如何创建具有可变参数/不同方法签名的方法接口(interface)?

php - 在类方法中调用函数?

linux - $VARIABLE 和 ${VARIABLE} 有什么区别

php - 在 PHP 中从父类访问重写的 protected 变量