0
按說我有一個名爲cache
一個對象,我想有cache.a
,cache.b
,cache.c
,......,從字面上每cache.whatever
使用預定義的價值VALUE
爲默認值,之前我明確地將其設置爲類似cache.a = 'FOOBAR'
。無論如何要實現這一目標?Javascript - 無論如何爲YET創建的屬性設置默認值?
按說我有一個名爲cache
一個對象,我想有cache.a
,cache.b
,cache.c
,......,從字面上每cache.whatever
使用預定義的價值VALUE
爲默認值,之前我明確地將其設置爲類似cache.a = 'FOOBAR'
。無論如何要實現這一目標?Javascript - 無論如何爲YET創建的屬性設置默認值?
你可以做到這一點像
function Cache(){
this.GetValue = function(propertyName){
if(!this[propertyName]){
this[propertyName] = "Value";
}
return this[propertyName];
}
this.SetValue = function(propertyName, Value){
this[propertyName] = Value;
}
return this;
}
編輯:
您可以使用它就像...
var cache = new Cache();
alert(cache.GetValue("a")); // It will alert "Value"
var newValueOfA = "New Value";
cache.SetValue("a", newValueOfA);
alert(cache.GetValue("a")); // It will alert "New Value"
沒有。最好的辦法是引入額外的間接層:
var Cache = function(){
this.values = {};
};
Cache.prototype.set = function(key, value) {
this.values[key] = value;
};
Cache.prototype.get = function(key) {
var result = this.values[key];
if (typeof result === 'undefined') {
return 'default';
}
return result;
};
以及如何使用它? – Kay
@Kay,檢查答案的編輯部分。 –
非常棒! =) – Kay