【问题标题】:How to reset na object property to the default one?如何将 na 对象属性重置为默认值?
【发布时间】:2012-11-12 02:08:24
【问题描述】:

我正在使用 jQuery,但我对 JavaScript 还是很陌生。我正在实现一个对象如下:

MyObject = {
  properties     : [{}],
  resetProperties: function resetProperties() { this.properties = [{}] }
};

正如您在上面的代码中看到的那样,我可以通过运行 MyObject.resetProperties() 来重置 properties,但是为了做到这一点,我声明了 两次 次 [{}] 变量。我应该如何在不重复该代码的情况下完成相同的事情?


更新

我尝试执行以下操作:

MyObject = {
  properties       : this.propertiesDefault,
  resetProperties  : function resetProperties() { this.properties = [{}] },
  propertiesDefault: [{}]
};

但我收到“TypeError: invalid 'in' operand MyObject.properties”,但我不确定这是正确的继续方式。

【问题讨论】:

    标签: javascript jquery object methods properties


    【解决方案1】:

    据我所知,这是不可能的。您将不得不对属性重置进行硬编码。我尝试在对象外部设置变量缓存,但是当我重置属性时,不幸的是它保持了它的值。

     var obj = {
         p: [ {} ],
         r: function() { this.p = this.cache; }
     };
    
     obj.cache = obj.p; // attempt to set to original
    
     obj.p[0].m = 5; // modify
    
     obj.r(); // reset
    
     --------
    
     >>> obj.p[0].m; // 5
    

    我们可以假设cache 属性的修改方式与p 相同。因此,我们不能那样重置。

    【讨论】:

      【解决方案2】:

      在我看来,避免将默认/重置属性作为要修改的对象的单独对象是不可能的。

      我建议使用默认值,并将其克隆到您的初始化和重置函数中。既然你用 jQuery 标记了你的问题,我假设你很乐意用它来克隆对象:

      MyObject = {
          defaultProperties : [{}],
          properties : jQuery.extend(true, {}, this.defaultProperties),
          resetProperties: function() { 
              this.properties = jQuery.extend(true, {}, this.defaultProperties);
          }
      };
      

      有关克隆对象的更多信息,请参阅此 Stack Overflow 问题:

      What is the most efficient way to deep clone an object in JavaScript?

      这是 jQuery.extend 的文档:

      http://docs.jquery.com/Utilities/jQuery.extend

      【讨论】:

      • 实际上,我不认为这种克隆方法(即使用jQuery)会起作用。但是,其他一些深度克隆方法应该适合您。也许是这样的:JSON.parse(JSON.stringify(this.defaultProperties));
      【解决方案3】:

      取决于你想要什么。由于您是 javascript 新手,您可能不熟悉使用函数创建自定义对象,这是一般的 javascript "OOP" 方式。

      function MyObjectClass() {
          this.properties = null;
          this.resetProperties();
      }
      MyObjectClass.prototype.resetProperties = function () { this.properties = [{}] };
      
      var MyObject= new MyObjectClass();
      

      但我们并不真正知道MyObject 需要实现的功能。可能需要它是一个普通的旧 javascript 对象。或者也许没有,你就完成了。

      当然,你总是可以直接:

      MyObject = {
                properties     : null,
                resetProperties: function () { this.properties = [{}];}
              };
      MyObject.resetProperties();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-11-15
        相关资源
        最近更新 更多