我在我的项目中使用了下划线,但现在我想使用underscore.string扩展它
我读了他们的文档,如果我不采取他们说要采取的额外措施,我可能会在使用这两种方法时遇到问题:
var _ = require('underscore');
// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)
_.str = require('underscore.string');
// Mix in non-conflict functions to Underscore namespace if you want
_.mixin(_.str.exports());
// All functions, include conflict, will be available through _.str object
_.str.include('Underscore.string', 'string'); // => true然而,我不知道如何遵循这些步骤,我需要帮助理解使用这两个步骤的步骤,并且使用它们没有问题。
到目前为止,我已经这样做了:
<script src="underscore-min.js" type="text/javascript"></script>
<script src="underscore.string.min.js" type="text/javascript"></script>还有另一个相关的问题,当我设法同时使用两者时,我必须始终使用_.str,还是只在冲突的函数上使用?
发布于 2012-02-14 03:12:12
How-To use underscore.string显然是为在node.js中使用而编写的,但是如果您想在html/js中使用它,您已经通过包含这两个库开始了。
下划线将创建_变量,如果存在,underscore.string将通过str和string属性对其进行扩展,因此您可以通过包含这两个文件来使用_.str。
<script src="underscore-min.js" type="text/javascript"></script>
<script src="underscore.string.min.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports()) </script>如果将最后一行添加到includes中,则可以使用underscore.string中任何非冲突方法,根据source file,这些方法都是include、contains和reverse。
希望这能有所帮助。
发布于 2015-06-20 08:03:49
在版本3.x中,只需使用全局s而不是下划线命名空间的_.mixin()。
这就是3.x版所需的全部内容
<script src="underscore-min.js" type="text/javascript"></script>
<script src="underscore.string.min.js" type="text/javascript"></script>现在不鼓励将
用作Underscore.js或Lo-Dash mixin,因为有太多冲突方法
发布于 2013-05-06 00:52:36
如果你想在每个函数上使用_而不是_.str (即使是有冲突的函数),你可以根据参数类型动态地选择冲突的方法:
(function(_contains, _include) {
_.mixin(_.str.exports());
_.mixin({
reverse: function(obj) {
if (typeof obj === "string") {
return _.str.reverse(obj);
}
return obj.reverse();
},
contains: function(obj, value) {
if (typeof obj === "string") {
return _.str.contains(obj, value);
}
return _contains.apply(this, arguments);
},
include: function(obj, value) {
if (typeof obj === "string") {
return _.str.include(obj, value);
}
return _include.apply(this, arguments);
}
});
})(_.contains, _.include);https://stackoverflow.com/questions/9265829
复制相似问题