en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Proxy and Reflect Article — Arrow Functions or `this` in Class constructor

Open NoelAbrahams opened this issue 2 years ago • 0 comments

Source: https://javascript.info/proxy Date Accessed: 1 March 2022

A serious limitation in ES6 Proxy is the inability to proxy internal use of the this context inside a class. In the password example, if we use a class, then the differences in behaviour from using an arrow function vs a method is clear:


class User {

  name = "John";
  _password = "***";

  checkPassword(value: string) {
    return value === this._password;
  }

  checkPassword2 = (value: string) => {
    return value === this._password;
  }
};

const user = new Proxy(new User(), {

  get(target: any, prop: string) {

    if (prop.startsWith('_')) {
      throw new Error("Access denied");
    }
    let value = target[prop];

    // Commenting out the workaround
    return value; // (typeof value === 'function') ? value.bind(target) : value; // (*)
  },
});

console.log(user.checkPassword2('***')); // Arrow function works without the workaround because `this` is the internal context
console.log(user.checkPassword('***')); // Method fails with `Access denied` as expected

The point here is that if your class passes this somewhere in the constructor then that this cannot be proxied. This is a significant limitation of Proxy and should probably be mentioned in the article.

A good write up BTW.

Thanks

NoelAbrahams avatar Mar 01 '22 20:03 NoelAbrahams