arthurfiorette / proposal-safe-assignment-operator

Draft for ECMAScript Error Safe Assignment Operator
https://arthur.run/proposal-safe-assignment-operator/
MIT License
1.08k stars 11 forks source link

Object methods not supported #18

Open robbiespeed opened 3 weeks ago

robbiespeed commented 3 weeks ago

Methods will loose their intended this value due to Function's Symbol.result wrapper which will override the this value to the method itself.

Ex:

const o = {
  r: 10,
  e: -10,
  method (v) {
    if (v > 0) {
     return this.r;
    } else {
      throw this.e;
    }
  }
};

o.method.r = 1000;

const [error, result] ?= o.method(2); // [null, 1000]

As you can see the this.r ends up retrieving it's value from o.method instead of o itself.

In it's current form Symbol.result can't preserve this, and it would also be very strange if it was a special case method on functions.

One solution is to change the signature of Function.prototype[Symbol.result] methods to match that of Function.prototype.call which is thisArg, ...arguments. So the code from the example would be equivalent to:

const [error, result] = o.method[Symbol.result].call(o, 2); // [null, 10]
anacierdem commented 3 weeks ago

Also related to #12