Javascript - 无论如何为已创建YET的属性设置默认值?

时间:2012-12-12 10:37:37

标签: javascript

据说我有一个名为cache的对象,我希望cache.acache.bcache.c,......,每个cache.whatever在我明确地将它们设置为VALUE之前,使用预定义值cache.a = 'FOOBAR'作为默认值。反正有没有实现这个目标?

2 个答案:

答案 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;
};