當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Underscore.js _.partial()用法及代碼示例

_.partial()函數用於通過填充任意數量的參數來部分應用該函數,而無需更改其動態值。

用法:

_.partial(function, *arguments)

參數:該函數接受上述和以下所述的兩個參數:

  • function:需要執行的函數。
  • arguments:此參數需要在元素之間添加一些符號。

返回值:此函數返回部分執行的函數的結果。

下麵的示例說明Underscore.js中的_.partial()函數:示例1:



<!DOCTYPE html> 
<html> 
  
<head> 
    <script type="text/javascript" src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script type="text/javascript"> 
  
        var product = function (num1, num2) { 
            return num1 * num2; 
        }; 
  
        prod = _.partial(product, 15); 
        console.log(prod(18)); 
    </script> 
</body> 
  
</html>

輸出:

範例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script type="text/javascript" src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script type="text/javascript"> 
  
        var sum = function (num1, num2, num3) { 
            return num1 + num2 + num3; 
        }; 
  
        sum = _.partial(sum, 15, 25); 
        console.log(sum(18)); 
    </script> 
</body> 
  
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自AshokJaiswal大神的英文原創作品 Underscore.js | _.partial() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。