2017-08-30 63 views
0

我想有一些看起来像这样布尔测试作为参数

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}
问题是,当我定义雪它引发错误,道具没有定义...
我明白这是因为我正在寻找重写一个变量甚至没有初始化,但我不知道如何实现一个布尔值测试作为一个功能

回答

2

的参数你需要一个functionarrow-function与输入参数传递到您的condition,它将被保存在cond道具。然后当您拨打func将一个参数传递给func并使用cond引用来调用cond function与给定的参数如cond(prop)。您也可以简化您的func功能,并仅参考cond

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`); 
 
}

+0

我从来没有见过没有()=> {},你能解释一下道具=>道具<0实际上是一个箭头的功能? –

1

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

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));

1

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

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));