In python, you can make an instance become a callable obj, like below shows:
# py code snippet
class Demo:
def __call__(self):
print("Demo's instance callable")
Demo()() # Demo's instance is callable
In js, is there the same feature like shown above?
// js code snippet
function Demo1() {}
const d1 = new Demo1();
class Demo2 {}
const d2 = new Demo2();
// can I make d1 or d2 become a callable instance? like d1() or d2() to run some function logic.
Another question:
What property or feature on Function
or Function.prototype
, make it’s instance is callable? Since I cant find any point of it on MDN Function page
2
Answers
You can’t call this directly, d1 and d2 are Demo instances, I recommend you to look at what happens in the process of new keyword in js, so you can understand, this is the implementation of the call method you described the code
I recommend you take a look at what the new keyword does so you can understand it
You can not do that. But you can achieve something like that…
Here’s my recommendation:
You’ll actually use the
BoundCallable
as your object which behaves the best like you intend it to.NOTE: As the generated function object prototype is a prototype of an object and not a function, then
BoundCallable
andCallableDemoObject
don’t pass the testinstanceof Function
, but they’re stillfunction
in atypeof
statement.