2012-12-12 39 views

回答

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" 
+0

以及如何使用它? – Kay

+0

@Kay,檢查答案的編輯部分。 –

+0

非常棒! =) – Kay

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; 
}; 
相關問題