布尔测试作为参数

时间:2017-08-30 07:43:02

标签: javascript function boolean conditional-statements

我希望看到像这样的东西

let condition = function(name, cond) {
this.name = name;
this.func = (prop) => {
    if (cond) { 
        return true;
    }
    return false;
}

let snow = new condition("temperature", prop < 0);

我在单独的文件夹上有一个temerature值,并且函数检查condition.func是返回true还是false。例如,如果温度低于0,它就不会下雪,这意味着我会调用condition.func(temperature),这将执行代码if (temperature < 0){return true}。 问题是,当我定义雪时,它会抛出未定义道具的错误...
我理解这是因为我想覆盖一个甚至没有初始化的变量,但我不知道如何将布尔测试作为函数的参数实现

3 个答案:

答案 0 :(得分:2)

您需要将带有输入参数的functionarrow-function传递给condition,并将其存储在cond道具中。然后,当您致电func时,将参数传递给func,并使用cond引用使用给定参数cond function调用您的cond(prop)。您也可以简化func功能,仅参考cond

&#13;
&#13;
let condition = function(name, cond) {
   this.name = name;
   this.func = cond;
};

let snow = new condition("temperature", prop => prop < 0);

if(snow.func(-2)){
  console.log(`Snowing`);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你可以在没有中间功能的情况下交出功能。对于条件,您需要一个函数,如p => p < 0,而不仅仅是一个条件,如prop < 0。这仅适用于硬编码或使用eval作为字符串,但不作为参数。

&#13;
&#13;
function Condition (name, cond) {
    this.name = name
    this.func = cond
}

let snow = new Condition("temperature", p => p < 0);

console.log(snow.func(5));
console.log(snow.func(-5));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您需要一种方法来检查该值是否与您的条件匹配。请参阅下面的可能解决方案。

&#13;
&#13;
let condition = function(name, predicate) {
  this.name = name
  // func will take a single value, the temperate to check
  this.func = (prop) => {
      // Execute the predicate method with the provided value.
      return predicate(prop);
  }
}

/**
 * This method will check your condition, it takes a single value as a param
 */
function snowPredicate(value) {
  // It can only snow when value is less than 0.
  return (value < 0);
}

// Set the condition for snow, pass the predicate method as the check.
let snow = new condition("temperature", snowPredicate)

// Check if it can snow when it is 10 degrees and -1 degrees.
console.log(snow.func(10));
console.log(snow.func(-1));
&#13;
&#13;
&#13;