How can I change the value of a private variable in a JavaScript method from outside?

I have an object o

. How can I change the value of a variable v

from 123 to 321 without overriding the entire method m

?

var o={
    p:123,
    m: function(a){
        var v=123;
        alert(v);
    }
};

      

+3


source to share


2 answers


Modify the object like this:

var o = {
    p: 123,
    v: 123,
    m: function(a) {
        var v = this.v;
        alert(v);
    }
};

      



Then, if you need to change v

on a case-by-case basis, just do:

o.v = 321;

      

+2


source


If you just want to override the value, then using a variable instead of a hard-coded value in the object would do the trick:

var x = 321;

var o = {
    p: 123,
    m: function(a) {
        var v = x;
        alert(v);
    }
};

      



At this point, when you call o.m(1);

, you get a warning with the value "321". If you then change the value x

to "456" o.m(1);

will return that value next time.

0


source







All Articles