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


underscore.js _.constant()用法及代碼示例


Underscore.js是一個JavaScript庫,它使對數組,字符串,對象的操作更加容易和方便。 _.constant()函數用於創建返回給定參數的函數。與_.identity()函數幾乎相同。

注意:在瀏覽器中使用下劃線函數之前,非常有必要鏈接下劃線CDN。鏈接underscore.js CDN時,“_”作為全局變量附加到瀏覽器。

用法:

_.constant( object );

參數:該函數接受單個參數對象。

返回值:該函數返回給定給函數的參數。



以下示例說明了Underscore.js中的_.constant()函數:

範例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script> 
  
        let str = "geeksforgeeks" 
  
        // _.constant function of underscore.js 
        let strFunc = _.constant(str); 
        console.log(`original str is:${str}`) 
        console.log(`str Function is:${strFunc}`) 
  
        // This will return true 
        console.log(str === strFunc()) 
  
        // Both strings are exactly same 
        console.log("from str:", str,  
            " from strFunc:", strFunc()); 
    </script> 
</body> 
  
</html>

輸出:

範例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> 
    </script> 
</head> 
  
<body> 
    <script> 
  
        // Creating a object 
        let obj = { 
            "a":"one", 
            "b":"two", 
            "c":"three" 
        } 
  
        // _.constant function of underscore.js 
        let objFunc = _.constant(obj); 
        console.log(`original object is:${obj}`) 
        console.log(`object Function is:${objFunc}`) 
  
        // This will return true 
        console.log(obj === objFunc()) 
  
        // Both objects are exactly same 
        console.log("from obj:", obj.a,  
            " from objFunc:", objFunc().a); 
  
        // Made Changes in object 
        obj.a = 12 
  
        // Change in one object reflects 
        // in another 
        console.log("change in one object " 
                + "reflects in another =>") 
                  
        console.log("from obj:", obj.a,  
            " from objFunc:", objFunc().a); 
    </script> 
</body> 
  
</html>

輸出:




相關用法


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