如何正确选择JavaScript模式

how to right choose javascript pattern

本文关键字:模式 JavaScript 选择 何正确      更新时间:2023-09-26

我创建 2 个对象:

  var Documentos = new QuadForm();
  var Cadastro = new QuadForm();

并使用许多选项初始化此对象

    Cadastro.initForm(options);
    Documentos.initForm(options2);

然后我尝试使用 getName 方法分离每个对象管理的数据,但在第二个对象之后,myObjectName 变量被覆盖。

    var QuadForm;
QuadForm = function () {
    this.getName = function () {
        // search through the global object for a name that resolves to this object
        for (var name in window)
            if (window[name] == this) {
                window[name] = this;
                window[window[name]] = window[name];
                myObjectName= name;
                break;
            }
    },
        this.initForm = function (parms) {
            this.getName()
            $.extend(this, parms);
            if (window.myState) {
                delete window.myState;
            }
            this.containerId = parms.formId;
            this.getForm(parms);
            this.workflowLabels('hide');

然后我使用 window[myObjectName].totalRecords,但当它更改为最新的对象名称时,当然无法访问数据。

我该如何管理。

管理多个实例不是什么大问题,但你的方法是不可能的,因为你无法真正找到所有可能的实例,而且你的代码绝对不是你期望的。

例如,您可以在包含所有实例的构造函数对象上定义一个变量,并且在某些情况下可以使用它:

var QuadForm = function (name) {
  this.name = name;
  QuadForm.instances.push(this);
  this.showAllOtherInstances = function () {
    QuadForm.instances.forEach(function (instance) {
      if (instance !== this) {
        console.log('name: ' + instance.name);
      }
    }.bind(this));
  }
}
QuadForm.instances = [];
var foo = new QuadForm('foo');
var anotherFoo = new QuadForm('foo');
var bar = new QuadForm('bar');
var aThirdFoo = new QuadForm('foo');
foo.showAllOtherInstances();
/* 
 * Output:
 *
 * name: foo
 * name: bar
 * name: foo
 */