【问题标题】:How to keep track of a previous value within a method in JavaScript?如何在 JavaScript 的方法中跟踪先前的值?
【发布时间】:2011-08-18 15:56:43
【问题描述】:

我需要将当前整数与方法中的前一个整数进行比较。似乎这样的事情应该有效,但事实并非如此。谁能告诉我问题出在哪里?注意当前是在方法之外设置的。

myMethod : function() {
    var previous;

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

    previous = current;
}

【问题讨论】:

  • 电流在哪里定义?你说的“它没有”是什么意思

标签: javascript variables methods


【解决方案1】:

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

【讨论】:

  • 你能举个例子说明你是如何使用第一个想法的吗?
【解决方案2】:

你只需要维护状态。

var previousState = 'something';

function myMethod(current)
{
    if(current > previousState)
       // Do Something

    previousState = current;
}

【讨论】:

    【解决方案3】:

    似乎您正在尝试实现记忆功能。有一个很好的教程告诉你如何去做here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2015-08-10
      • 2018-04-22
      • 2015-06-05
      相关资源
      最近更新 更多