JavaScript equivalent of Python's __setitem__

Is it possible to implement __setitem__ behavior in JavaScript?

No. There is no getter/setter for arbitrary properties in JavaScript.

In Firefox you can use JavaScript 1.5+'s getters and setters to define x and y properties that square their values on assignment, eg.:

var obj= {
    _x: 0,
    get x() { return this._x; },
    set x(v) { this._x=v*v; }
};
obj.x= 4;
alert(obj.x);

but you would have to declare a setter for each named property you wanted to use in advance. And it won't work cross-browser.


No, but there are plans for supporting a similar feature in JavaScript 2. The following object literal syntax has been suggested on Mozilla bug 312116 and it seems that it might be how it will be done for object literals:

({
  get * (property) {
    // handle property gets here
  }
})

I'm assuming set would also be supported (as set * (property, value) {...}).


you can do this (as objects in javascript are also associative arrays):

var obj = {};
obj._ = function(key, value){
  this[key] = value * value;
}
obj._('x', 2);  // 4
obj._('y', 3);  // 9

alert(obj.x + "," + obj.y); //--> 4,9