2014-10-22 55 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函数更改变量的值。