JS alternative of Ruby’s method_missing
Why? Because!- Jul 4, 2017
- 1 min read
- #guides
- #javascript
- #metaprogramming
Warning
This post was written more than 5 years ago, and its contents may be out of date
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" }
Comments