Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to I make 2 Javascript variables be equal to each other at all times?

How to I make 2 Javascript variables be equal to each other at all times?

Problem

I'm trying to implement the node.js module.exports and exports rule in a script. These 2 variables should be equal to each other at all times. Even when one changes the other one should change too.

I tried doing this with setters, but both o.foo and o.bar end up undefined =/

var foo = { hello: 'world' };
var o = {
  foo: foo,
  bar: foo
};


var inuse = false;
var setter = function(val) {
  if (inuse) return;
  inuse = true;
  o.foo = val;
  o.bar = val;
  inuse = false;
};
o.__defineSetter__('foo', setter);
o.__defineSetter__('bar', setter);

o.foo = { hey: 'there' };

console.log(o.foo);
console.log(o.bar);
Problem courtesy of: fent

Solution

Create getters as well, and assign to different property names.

DEMO: http://jsfiddle.net/jqExh/

var foo = { hello: 'world' };
var o = {
  _foo: foo,
  _bar: foo
};

var inuse = false;

var setter = function(val) {
  if (inuse) return;
  inuse = true;
  this._foo = val;
  this._bar = val;
  inuse = false;
};
o.__defineGetter__('foo',function(){return this._foo;});
o.__defineGetter__('bar',function(){return this._bar;});
o.__defineSetter__('foo', setter);
o.__defineSetter__('bar', setter);

o.foo = { hey: 'there' };

console.log( o.foo ); // Object
console.log( o.bar ); // Object

console.log( o.foo === o.bar ); // true

console.log( o.foo.hey, o.bar.hey ); // there there

Or use variables instead of properties:

DEMO: http://jsfiddle.net/jqExh/1/

var o = (function() {
    var foo = { hello: 'world' };

    var _foo = foo;
    var _bar = foo;

    var _o = {};

    var inuse = false;

    var setter = function(val) {
      if (inuse) return;
      inuse = true;
      _foo = val;
      _bar = val;
      inuse = false;
    };
    _o.__defineGetter__('foo',function(){return _foo;});
    _o.__defineGetter__('bar',function(){return _bar;});
    _o.__defineSetter__('foo', setter);
    _o.__defineSetter__('bar', setter);

    return _o;
})();

o.foo = { hey: 'there' };

console.log( o.foo );
console.log( o.bar );

console.log( o.foo === o.bar ); // true

console.log( o.foo.hey, o.bar.hey ); // there there

This way the only way to get and set them is via the accessors.

Solution courtesy of: user113716

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to I make 2 Javascript variables be equal to each other at all times?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×