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


Lodash _.wrap()用法及代码示例

lodash中的Function的_.wrap()方法用于创建一个函数,该函数像其初始参数一样将值传递给指定的包装器。此外,传递给该函数的任何其他参数都将添加到传递给所述包装器的参数中。

注意:

  • 此处使用的包装器通过所形成函数的this绑定进行调用。

用法:

_.wrap(value, [wrapper=identity])

参数:此方法接受上面提到和下面描述的两个参数:

  • value:它是要包装的值。
  • wrapper:它是包装器函数。

返回值:此方法返回新函数。



以下示例说明了JavaScript中的Lodash _.wrap()方法:

范例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Calling wrap() method with its parameter 
var res = _.wrap(_.escape, function(functn, txt) { 
  return '<b>' + functn(txt) + '</b>'; 
}); 
   
// Assigning values 
res('GfG, geeks, & GeeksforGeeks');

输出:

<b>GfG, geeks, &amp; GeeksforGeeks</b>

范例2:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Calling wrap() method with its parameter 
var newfn = _.wrap(_.upperCase, function(x, y) { 
  return x(y) 
}); 
  
// Assigning values 
newfn("geeksforgeeks");

输出:

GEEKSFORGEEKS

参考: https://lodash.com/docs/4.17.15#wrap

相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Lodash _.wrap() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。