Search code examples
javascriptdefineproperty

how to overload = operator with js es5 Object.defineProperty


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) ?


Solution

  • 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.