Here's an intriguing challenge for JavaScript enthusiasts
Can you intercept property access in JavaScript using proxies?
By applying a clever hack like the one demonstrated below, it's possible to intercept static property access within a class:
class Handler{
constructor(object){
this.object = object;
}
get(target, property){
if (property === 'all') {
return () => `selecting data from table: ${this.object.table}` ;
}
return target[property];
}
}
class User{
static table = 'users'
}
Object.setPrototypeOf(User, new Proxy({}, new Handler(User)));
console.log(User.all()); // prints "selecting data from table: users"
The issue arises when attempting to extend the User
class and then invoking a static method from the parent class of User
:
class Handler{
constructor(object){
this.object = object;
}
get(target, property){
if (property === 'all') {
return () => `selecting data from table: ${this.object.getTable()}` ;
}
return target[property];
}
}
class Model{
static getTable(){return this.table;}
}
class User extends Model{
static table = 'users'
}
Object.setPrototypeOf(User, new Proxy({}, new Handler(User)));
console.log(User.all());
Executing this code will result in
TypeError: this.object.getTable is not a function
.
Upon closer inspection, I discovered that this.object
is not a User
class but rather some kind of a function
.
Is there a way, through any workaround, to invoke the parent's static method getTable
?
The second issue, even if you resolve the first one, is that instantiating the User
class becomes impossible:
console.log(new User());
TypeError: Super constructor [object Object] of User is not a constructor
I suspect this is because User
no longer functions as a class: console.log(User)
yields ƒ [object Function]
instead of class User extends Model
Does JavaScript support this type of functionality?