创建Undercore中使用的安全参考对象技术

Create a safe reference object technique used in Underscore

本文关键字:安全 参考 对象 技术 Undercore 创建      更新时间:2023-09-26

当我浏览Underscore中的代码时:http://underscorejs.org/docs/underscore.html

我偶然发现

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

带注释

创建对Undercore对象的安全引用,以便在下面使用。

我真的不明白目的。而不是

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

为什么我们不能简单地拥有

(function() {
    var _ = {};
    _.VERSION = '1.7.0';
})();

我可以知道Underscore项目使用技术背后的想法吗?

这强制使用构造函数模式创建对象:_()将等效于new _()

然后,如果你想扩展用_(obj)(或new _(obj))创建的所有实例ie对象的行为,并且内存使用有限,你可以扩展构造函数的原型。

function Ctor(){}
Ctor.prototype.someFunction=function(){};
var instance1=new Ctor();
var instance2=new Ctor();

在某种程度上等同于

function factory(){
   var obj={};
   obj.someFunction=function(){}
   return obj;
}
var instance1=factory();
var instance2=factory();

但是第二个版本将使用更多的内存,因为它将把函数添加到每个实例,而不是单个通用原型