我有一个对象,如果尚未注册操作目标,我打算返回一个新实例。一个非常简化的代码版本:
var Tangler = (function () {
var targets = [], /* Array of targets Tangler operates on, no dupes. */
registry = []; /* Array of Tanglers operating on targets. */
/* Register new Tangler */
function Tangler_entity(target) {
this.id = registry.length;
targets.push(target);
registry.push(this);
return this;
}
/* Public initiator.
* Returns existing Tangler if one with target exists. */
function Tangler(target) {
var i;
if (!target)
return null;
for (i = 0; i < targets.length; ++i) {
if (targets[i] === target)
return registry[i]; /* Return existing Tangler. */
}
return new Tangler_entity(target); /* Return new Tangler. */
}
Tangler.prototype.some_function = function () {
/* Operate on targets[this.id] */
};
return Tangler;
})();
现在,意图是将其用作:
var tang = Tangler(some_target);
但是,运行此代码会发生什么?:
var tang = new Tangler(some_target);
他们似乎都运行正常,因为在正确的目标中获得更新,new new
上没有产生任何欺骗。