Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make an object 'callable'?

Tags:

javascript

Is it possible to make an object callable by implementing either call or apply on it, or in some other way? E.g.:

var obj = {}; obj.call = function (context, arg1, arg2, ...) {     ... };  ...  obj (a, b); 
like image 979
Septagram Avatar asked Oct 12 '13 15:10

Septagram


People also ask

How do you make an object callable in Python?

The “calling” is achieved by placing a pair of parentheses following the function name, and some people refer to the parentheses as the call operator. Without the parentheses, Python interpreter will just generate a prompt about the function as an object itself — the function doesn't get called.

How do you make a class object callable?

To make a class instance callable, all you need to do is implement a __call__ method. Then, to call the __call__ method, you just do: instance(arg1,arg2,...) -- in other words, you call the instance the same way you would call a function.

Is an object callable?

A callable object, in computer programming, is any object that can be called like a function.

Are Python objects callable?

Python's functions are callable objects So, every function in Python is a callable, meaning it's an object that you're able to call.


2 Answers

No, but you can add properties onto a function, e.g.

function foo(){} foo.myProperty = "whatever"; 

EDIT: to "make" an object callable, you'll still have to do the above, but it might look something like:

// Augments func with object's properties function makeCallable(object, func){     for(var prop in object){         if(object.hasOwnProperty(prop)){             func[prop] = object[prop];         }     } } 

And then you'd just use the "func" function instead of the object. Really all this method does is copy properties between two objects, but...it might help you.

like image 182
Max Avatar answered Sep 21 '22 02:09

Max


ES6 has better solution for this now. If you create your objects in a different way (using class, extending 'Function' type), you can have a callable instance of it.

See also: How to extend Function with ES6 classes?

like image 21
0xc0de Avatar answered Sep 19 '22 02:09

0xc0de