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

Cof*_*fey 3 javascript variables methods

我需要将当前整数与方法中的先前整数进行比较。看起来像这样的事情应该有效,但事实并非如此。有人能告诉我问题出在哪里吗?注意电流是在方法之外设置的。

myMethod : function() {
    var previous;

    if ( current > previous ) {
        // do this!
    }

    previous = current;
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 5

每次调用时myMethodprevious都会重新声明 ( var previous)。

你有四种可能:

(A)创建一个闭包(最好的解决方案imo,但取决于您的需求):

myMethod : (function() {
    var previous = null;
    return function() {
        if ( current > previous ) {
            // do this!
        }  
        previous = current;
    }
}());
Run Code Online (Sandbox Code Playgroud)

(B) 设置previous为函数对象的属性:

myMethod : function() {
    if ( current > foo.myMethod.previous ) {
        // do this!
    }   
    foo.myMethod.previous = current;
}

foo.myMethod.previous = null;
Run Code Online (Sandbox Code Playgroud)

但这将功能与对象的命名联系在一起。

(C) 如果它适合您的模型,则使previous对象myMethod的属性是以下属性:

previous: null,
myMethod : function() {
    if ( current > this.previous ) {
        // do this!
    }
    this.previous = current;
}
Run Code Online (Sandbox Code Playgroud)

(D) 与 (A) 类似,设置previous在更高范围之外的某处:

var previous = null;
// ...
myMethod : function() {

    if ( current > previous ) {
        // do this!
    }  
    previous = current;
}
Run Code Online (Sandbox Code Playgroud)

这不是一个好的 imo,因为它会污染更高的范围。

没有看到更多的代码很难判断,但是当你传递current给函数时它可能也会更好。