2012-11-23 60 views
1

我正在使用jQuery,而我對JavaScript仍然很陌生。我在執行對象爲以下幾點:如何將na對象屬性重置爲默認值?

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」,我不知道這是正確的前進道路。

回答

1

在我看來,不可能避免將默認/重置屬性作爲單獨對象與將要修改的對象相關聯。

我會建議有一個默認值,並克隆它在你的初始化和重置功能。既然你用jQuery標記你的問題,我想你是快樂的克隆與對象:

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

參見克隆對象的詳細信息,這個堆棧溢出問題:

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

這是對於jQuery.extend文檔:

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

+0

請參閱我的更新。 – user12882

+0

其實,我不認爲這種克隆方法(即使用jQuery)會起作用。但是其他一些深度克隆方法應該適合您。也許是這樣的:JSON.parse(JSON.stringify(this.defaultProperties)); – null

0

從我知道這是不可能的。你將不得不硬編碼屬性重置。我嘗試在對象外部設置變量緩存,但是當我重置屬性時,它不幸保持其值。

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是。因此,我們不能像那樣重置。

0

取決於你想要什麼。由於你是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(); 
相關問題