Javascript-是否为尚未创建的属性设置默认值?
假设我有一个名为Javascript-是否为尚未创建的属性设置默认值?,javascript,Javascript,假设我有一个名为cache的对象,我希望有cache.a,cache.b,cache.c,…,实际上是每个缓存。在我显式地将它们设置为cache.a='FOOBAR'之前,使用预定义值作为默认值。有没有办法做到这一点?没有。最好的办法是引入额外的间接层: var Cache = function(){ this.values = {}; }; Cache.prototype.set = function(key, value) { this.values[key] = value; }
cache
的对象,我希望有cache.a
,cache.b
,cache.c
,…,实际上是每个缓存。在我显式地将它们设置为cache.a='FOOBAR'
之前,使用预定义值作为默认值。有没有办法做到这一点?没有。最好的办法是引入额外的间接层:
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;
};
你可以这样做
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"
@凯,检查答案的编辑部分。