什么是这个underscore.js“安全参考”代码做什么? [英] what is this underscore.js "safe reference" code doing?

查看:122
本文介绍了什么是这个underscore.js“安全参考”代码做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Backbone,它使用的是Underscore。

I'm learning Backbone, which uses Underscore.

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

In some examples, I see initialization code to create an empty array of children like this:

// inside a constructor function for a view object that will be extended:
this.children = _([]);

上面调用的下划线函数 _ 是在Underscore.js顶部附近定义:

The Underscore function _ above being called is defined near top of Underscore.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;
};

在调试器中单步执行显示返回新_(obj)<首先调用/ code>,因此再次调用该函数,最后执行 this._wrapped = obj 似乎是指 _

Stepping through in the debugger shows me the return new _(obj) is called at first, so the function is called again and finally this._wrapped = obj is executed. this appears to be referring to _.

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

I am bewildered. Why not just say this.children = [] in the first place?

推荐答案

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

Because this.children needs to be a instance of underscore: a specialized class that wraps an array, not just a regular javascript array literal. The code in the _ function just makes sure it's always one _ instance wrapping one regular array, even if you try to rewrap an underscore instance repeatedly, call _ with or without the new keyword.

//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);

这篇关于什么是这个underscore.js“安全参考”代码做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆