2014-10-22 53 views
0

有什麼辦法,在JavaScript中,寫這樣一個功能:JavaScript函數編輯原始對象

var a = "Hello" 

function change(variable, value) { 
//Code that edits original variable, not the variable argument 
} 

alert(a) 
change(a, "World!"); 
alert(a); 

,這將首先輸出「你好」,然後在「世界!」。有什麼辦法可以寫出這樣的功能嗎?

+1

不,但您可以將該值封裝在對象中,並將其修改爲對象的屬性。 – 2014-10-22 04:53:16

回答

0

否,但接近的替代方法是治療a作爲JS對象:

var a = { value : "Hello" }; 

function change(variable, value) { 
    //I'll let you work this part out 
} 

alert(a.value); 
change(a, "World!"); 
alert(a.value); 
+0

謝謝,習慣的力量:) – 2014-10-22 04:56:17

0

這裏是你如何做到這一點通過使用JavaScript閉包;

var obj = (function() { 
      var x = 'hello'; 
      return { 
        get: function() { 
         return x; 
        }, 
        set: function(v) { 
         x = v; } 
        } 
        })(); 

obj.get(); // hello 
obj.set('world'); 
obj.get(); // world 

您只能使用get和set函數更改變量的值。