JSFiddle - React, Tailwind, and code Playground
by SanjayVyas
JavaScript
//% JavaScript does not have Dart like noSuchMethod
//% It's easy to build it using Proxy()
//# [Sanjay Vyas]
class Person {
constructor(id, name) {
this.id = id;
this.name = name;
}
//~* If the class defines noSuchMethod, proxy will call it
noSuchMethod(methodName) {
console.log(`You called a missing method '${methodName}'`);
}
print() {
console.log(this.id, this.name);
}
}
//~# dynamic Proxy to intercept method calls and invoke noSuchMethod
const dynamic = (classOrObject, ...args) =>
new Proxy(typeof (classOrObject) == "function" && classOrObject.constructor
? new classOrObject(...args)
: classOrObject,
{
get(target, property, receiver) {
let method = Reflect.get(target, property, receiver);
if (method)
return method;
if (target["noSuchMethod"])
return () => target["noSuchMethod"](property, ...args);
}
}
);
let newObj = dynamic(Person, 1, "Eich");
newObj.prin(); //~! Will result in call of noSuchMethod
let person = new Person(2, "Brendan");
let existingObj = dynamic(person);
existingObj.prin(); //~! Will result in call of noSuchMethod