TL:DR; Is it possible to make a property of object to be invocable ( as a function ) only ?
What i mean by this
class Foo{
bar(value){
return value
}
}
let newFoo = new Foo()
console.log(newFoo.bar(123)) // should work fine as function is invoked
console.log(newFoo.bar) // here i need to throw or display an error instead of returning value
I tried to do this with Proxy and handler.get trap, but i have no clue how to capture whether it is a function call or just property access,
class Foo {
bar(value) {
return value
}
}
const proxied = new Proxy(new Foo(), {
get: function(target, prop, reciver) {
if (prop === 'bar') {
throw new Error('Bar is method need to be invoced')
}
return target[prop]
}
})
console.log(proxied.bar(true))
console.log(proxied.bar)
I have also checked handler.apply but this also doesn't seems to be of no use as this is a trap on function, not on property
class Foo {
bar(value) {
return value
}
}
const proxied = new Proxy(new Foo(), {
apply: function(target, thisArg, argumentsList) {
return target(argumentsList[0])
},
get: function(target, prop, reciver) {
if (prop === 'bar') {
throw new Error('Bar is method need to be invoced')
}
return target[prop]
}
})
console.log(proxied.bar(true))
console.log(proxied.bar)
newFoo.barwill be evaluated as an expression before the subsequent argument list gets applied to the prior expression, so if accessingnewFoo.barthrows, callingnewFoo.barwould have to throw too.accessor will return property and then that will be invoked, but not sure, as there are always way to achieve a thing in JS, so hoping if there's anyway to do soXYproblem i am not sure though, i tired with whatever knowledge i have about proxies and couldn't succeed, so here i am asking from people if there's any other way it can be done, or in first place can it be done at allgetbeforecallas far as I know, you can check if its called after theget, so something like this jsfiddle.net/y52khqs8