JS alternative of Ruby’s method_missing

Some guy in telegram JS chat asked how to do something like this:

let types = new Types()console.log(types.AnythingYouCouldImagine({ a: "some data" }))// { type: "AnythingYouCouldImagine", data: { a: "some data" } }

In ruby we can use handy method_missing callback, but in js we don’t have anything that can turn any class into this. But in js we have thing called proxy.

This will work like “catchall”:

let proxy = new Proxy({}, {
get(target, prop) {
return (data) => {
return {
type: prop,
data: data
}
}
}
})

console.log(proxy.Anything('data'))
// { type: "Anything", data: "data" }

And this one will work like method_missing:

class A {
alreadyDefined (arg) {
return { a: "Wow!", arg: arg }
}
}
let proxy = new Proxy(new A(), {
get(target, prop) {
if(target[prop]) return target[prop]

return (data) => {
return {
type: prop,
data: data
}
}
}
})

console.log(proxy.alreadyDefined('data'))
// { a: "Wow!", arg: "data "}
console.log(proxy.Anything('data'))
// { type: "Anything", data: "data" }

Immolate Improved