Unfortunately, in JavaScript, ES5 getter-setters can intercept assignments using the specified methods, but there is no built-in operator overloading mechanism to intercept and modify operations like +
or +=
.
One workaround could involve special handling for primitive values when adding them.
var appendable = {
x_: [1, 2],
get x() { return this.x_; },
set x(newx) { this.x_.push(newx.substring(("" + this.x_).length)); }
};
alert(appendable.x);
appendable.x += 3;
alert(appendable.x); // This will display 1,2,3 instead of 1,23
alert(appendable.x.length);
However, it's worth noting that using the .push
method is generally recommended for appending elements to an array.