当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。