0

I what to overload the = operator for JS objects using Object.defineProperty.

var log = console.log.bind(console);
var obj = { };
Object.defineProperty(obj,'var', {
  get: function() { log('get'); return obj._var; },
  set: function(v) { log('set'); obj._var = v; }
});

That's the standard es5 syntax for defining a simple property.
Now obj.var is a property with overloaded = operator.
But what i actually what to do is to overload = operator for the obj itself.

obj.var = 'a'; // prints: get
var v = obj.var;
v = 'b';  // prints: nothing!
// of course that's right, because v is an string now.

How to overload the = operator for the object itself ?

//i what something like this 
v = 'b'; // should print: set

Is it possible (in es5) ?

amin
  • 3,672
  • 5
  • 33
  • 61

2 Answers2

2

No, this is not possible. You are in fact not overloading the = operator, you are overloading the . operator (or property accessors in general). Your getter / setter will be called whenever the property of your object is used. v is no more a property, it's just a variable that holds a value.


That said, while you cannot do this for arbitrary variables, the with statement does allow you to write code that looks like variable assignment and does what you expected:

with({
  get v() { console.log("get"); return 5; },
  set v(x) { console.log("set", x); }
}) {
  v = 5; // set 5
  console.log(v); // get, 5
}

Notice that this is really really scary and you really really should not do this. It's banned from strict mode for good reason.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can copy the property descriptor onto another object, but this may give unexpected results depending on how things are referenced (e.g. you reference obj._var, but a similar implementation could use this._var or a closure) – Paul S.

@PaulS. can you give an example. thanks. – amin

Say you have your definition set up

var log = console.log.bind(console);
var obj = { };
Object.defineProperty(obj,'var', {
  get: function() { log('get'); return obj._var; },
  set: function(v) { log('set'); obj._var = v; }
});

Now copy the descriptor onto another Object,

var o2 = {}; // another object
Object.defineProperty(
    o2, 'copied_var',
    Object.getOwnPropertyDescriptor(obj, 'var')
);

Then you can use these getters and setters through this different object

o2.copied_var = 1; // logs set
o2.copied_var;    // 1, logs get

But notice because of the reference in the functions is to obj._var we have

o2._var; // undefined
obj._var; // 1
obj.var; // 1 (same lookup), logs get
Paul S.
  • 64,864
  • 9
  • 122
  • 138