假设我有一个名为 的对象,并且cache
在我明确地将它们设置为. 有没有办法做到这一点?cache.a
cache.b
cache.c
cache.whatever
VALUE
cache.a = 'FOOBAR'
问问题
46 次
2 回答
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"
于 2012-12-12T10:54:31.173 回答
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;
};
于 2012-12-12T10:45:44.603 回答