据说我有一个名为cache
的对象,我希望cache.a
,cache.b
,cache.c
,......,每个cache.whatever
在我明确地将它们设置为VALUE
之前,使用预定义值cache.a = 'FOOBAR'
作为默认值。反正有没有实现这个目标?
答案 0 :(得分:1)
你可以这样做
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"
答案 1 :(得分:0)
不。最好的办法是引入额外的间接层:
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;
};