2017-08-30 65 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));