Eric
Eric

Reputation: 3006

How do you give variables reference in javascript?

I want to give variables reference in javascript.

For example, I want to do:

a=1
b=a
a=2

and have b=2, and change accordingly to a.

Is this possible in javascript? If it isn't is there a way to do like a.onchange = function () {b=a}?

What I wanted to do was make a function like makeobject which make an object and puts it in an array and than returns it like

function makeobject() {
   objects[objects.length] = {blah:'whatever',foo:8};
   }

so than I could do

a=makeobject()
b=makeobject()
c=makeobject()

and later in the code do

for (i in objects) {
   objects[i].blah = 'whatev';
}

and also change the values of a,b and c

Upvotes: 4

Views: 284

Answers (3)

Demian Brecht
Demian Brecht

Reputation: 21378

It's kind of possible. You'd have to use an object however:

var a = new Object();
a.val = 6;

alert(a.val);

var b = a;
b.val = 5;

alert(a.val);

Edit: I was playing around with another alternative (even though an answer was already marked), and here's another solution:

function makeobj()
{
    if(typeof makeobj.baseobj === 'undefined')
    {
        makeobj.baseobj = { 'blah': 'whatever', 'foo': 8 };
    }
    return makeobj.baseobj;
}

var a = makeobj();
var b = makeobj();
var c = makeobj();

alert(a['blah']);
alert(b['blah']);
alert(c['blah']);

b['blah'] = 'i changed the value';

alert(a['blah']);
alert(b['blah']);
alert(c['blah']);

The alternative solution will allow you to create n objects and change the values whenever you want and have the changes propagate to other variables created by the makeobj() function.

Upvotes: 2

ChaosPandion
ChaosPandion

Reputation: 78292

You can pull this off using the new object literal syntax which works well in most browsers.

var o = {
    _a : null,
    get a() { return this._a; },
    set a(v) { this._a = v; },
    get b() { return this._a; },
    set b(v) { this._a = v; }
};

o.a = 2;
o.b = 3;
o.a = 4;
alert(o.b); // alerts 4

Another alternative is to create your own reference object.

function Ref(obj, name, otherName) {
    this.obj = obj;
    this.name = name;
    this.otherName = otherName;
}

Ref.prototype.assign = function (v) {
    this.obj[this.name] = this.obj[this.otherName] = v;
}

var o = {
    a : 1,
    b : 4
};

var ref = new Ref(o, 'a', 'b');
ref.assign(3);

alert(o.b);

Upvotes: 5

SLaks
SLaks

Reputation: 888185

This is not possible.

What are you trying to do?
We can probably find you more Javascript-y ways to do it.

Upvotes: 0

Related Questions