Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 这是什么下划线.js;安全参考“;代码在做什么?_Javascript_Underscore.js - Fatal编程技术网

Javascript 这是什么下划线.js;安全参考“;代码在做什么?

Javascript 这是什么下划线.js;安全参考“;代码在做什么?,javascript,underscore.js,Javascript,Underscore.js,我正在学习主干,它使用下划线 在一些示例中,我看到初始化代码创建一个空的子数组,如下所示: // inside a constructor function for a view object that will be extended: this.children = _([]); 上面被调用的下划线函数\uu是在underline.js顶部附近定义的: // Create a safe reference to the Underscore object for use below. va

我正在学习主干,它使用下划线

在一些示例中,我看到初始化代码创建一个空的子数组,如下所示:

// inside a constructor function for a view object that will be extended:
this.children = _([]);
上面被调用的下划线函数
\uu
是在underline.js顶部附近定义的:

// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
};
在调试器中单步执行显示,首先调用
returnnew(obj)
,因此再次调用函数,最后执行
this.\u wrapped=obj
<代码>此似乎指的是
\u


我很困惑。为什么不首先说
this.children=[]

因为
this.children
需要是下划线的实例:一个封装数组的专用类,而不仅仅是一个常规javascript数组文本。
函数中的代码只是确保它始终是一个包含一个常规数组的
实例,即使您尝试重复重写下划线实例,也可以使用或不使用
new
关键字调用

//new _ instance wrapping an array. Straightforward.
var _withNew = new _([]);

//automatically calls `new` for you and returns that, resulting in same as above
var _withoutNew = _([]);

//just gives you _withoutNew back since it's already a proper _ instance
var _doubleWrapped = _(_withoutNew);

根据您的偏好,可以在面向对象样式或函数样式中使用下划线。以下两行代码是将数字列表加倍的相同方法

_.map([1, 2, 3], function(n){ return n * 2; }); // Functional style
_([1, 2, 3]).map(function(n){ return n * 2; }); // OO style
因此,在使用OO样式时,\被用作构造函数。如果构造函数中没有“创建对下划线对象的安全引用”的前两行,则必须使用
new
关键字,如下所示

new _([1, 2, 3]).map(function(n){ return n * 2; });

现在你没有:)

我理解你对发生的事情的解释,但我还是有点不清楚为什么。js库定义了函数
,该函数上定义了许多属性(主要是函数)。为什么我希望我的数组是下划线的实例?这是否允许我使用下划线数组和集合函数作为数组的方法,而不是按照文档建议的方式传递数组,例如
\uuuu.first(array,[n])
。即使这是真的,像
.isNaN(object)
这样的函数呢。这对我的数组有什么好处?是的,这样您就可以将数组转换为支持的下划线数组,然后在以后使用下划线函数。虽然我不认为这样做很常见,但我相信这是最外层的
函数本身的意图代码片段?我对类似于thoughtbot的PDF书的东西感兴趣。