0

在 JavaScript 中,是否可以测试一个条件是否在程序的整个执行过程中保持为真?在这里,我想确保变量 a 从程序开始到结束始终可以被 3 整除。

//Assert that the following is always true, and print an error message if not true
ensureAlwaysTrue(a % 3 == 0); //print an error message if a is not divisible by 0
                              //from this point onward

a = 6;

a = 10 //print error message, since a % 3 != 0

function ensureAlwaysTrue(){
    //this is the function that I'm trying to implement.
}

一种解决方案是在每个变量赋值后添加语句来检查断言,但这将是多余和麻烦的。是否有更简洁的方法来检查整个程序执行过程中条件是否为真?

4

4 回答 4

3

哇,这些都是可怕的解决方案。如果您真的想这样做,您可以创建一个模型并使用模型上的方法访问该值。这是一个例子:

function Model(value){
  this.value = value;
}

Model.prototype = {
  get: function(){
    return this.value;
  },

  set: function(value){
    if(this.validate(value)){
      this.value = value;
      return this;
    }
    throw Error('Not a valid value.');
  },

  test: function(func){
    this.validate = func;
    return this;
  }
};

var a = new Model();

a.test(function(val){ return val == 7 });

// Sets value of a to 7
a.set(7);
// Gets value of a (7 in this case)
a.get();
// Throws an error
a.set(5);
于 2013-01-26T08:00:16.250 回答
2

不。

您可能在 Javascript 中获得的最接近的方法是找到一些“编译”您的代码以ensure在每个语句之后自动注入函数调用的工具,例如用于 Java 的AspectJ 。

使用另一种语言的潜在方法可能是使用后台线程。Javascript 线程(网络工作者)将无法访问其他线程中的变量。Javascript 也是一种解释性语言,它只会按顺序运行代码——除非ensure函数实际上在执行路径中,否则它不会执行。

于 2013-01-26T04:57:30.343 回答
1

好吧,你可以添加一个定时间隔,比如

assertInterval = 10; //milisseconds

function ensureAlwaysTrue(condition)
{
    setInterval(function(){ if(!condition()) error(); }, assertInterval);
}

你会这样称呼它:

var a = 6;

ensureAlwaysTrue(function(){return (a % 3 == 0);});

那会抓住它,但最多有assertInterval几毫秒的延迟。

编辑: 它实际上不起作用,正如@Chris 指出的那样:“您的间隔函数实际上不会在当前执行函数的语句之间运行”。这是真的,它只适用于事件之间的断言等。

于 2013-01-26T05:00:18.830 回答
0

根据@Chris (http://stackoverflow.com/a/14534019/1394841) 的想法,您可以将整个代码包含在一个字符串中,然后执行以下操作:

function ensureAlwaysTrue(condition, code)
{
    var statements = code.split(";");
    for (var i = 0; i < statements.length-1; i++) { //last statement is empty
        eval(statements[i] + ";");
        if (!condition()) error();
        //break; //if desired
    }
}

var code =
"a = 6;\
a = 10; //print error message, since a % 3 != 0\
";

ensureAlwaysTrue(function(){return (a % 3 == 0);}, code);
于 2013-01-26T05:22:06.167 回答