首页 > Underscore的Create a safe reference object有什么作用

Underscore的Create a safe reference object有什么作用

var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

这个函数写的妙不妙,如果你觉得妙,请分析下它的精妙之处?


这是underscore的源码吧,为了:

Create a safe reference to the Underscore object for use below.

目的是,当使用者这样调用:(第一次)

_(obj)

就会返回:new _(obj)

然后就会再次调用到:

this._wrapped = obj;

以后对于_(obj)的调用都会返回this._wrapped,不会多余的new了。

怎么用?

var powerArray = _([]) // 此时powerArray,除了array本身的方法也拥有了underscore提供的增强方法
powerArray.push(1)
powerArray.push(2) // [1,2]
powerArray.min() // 1 (min方法就是underscore提供的)

变量名见名知意,一看这函数就没意义。

【热门文章】
【热门文章】