Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Objects as Functions JavaScript

In JavaScript, functions are objects, except that they can be called and executed, this is comparable to overloading the () operator of an object in other languages.

Can I apply this functionality to any object?

I know there isn't a property like [Symbol.call] or something comparable. If there is something comparable, I would greatly appreciate it if you could inform me of what it is.

If declaring objects and assigning properties to them is my only option that's okay, but I'd prefer if this could be done using a class, like C++ for example.

I could do something like this

function func(...) {
...
}

func.foo = x,
func.bar = y;

but it would be more preferable if I could do something more like

const func = {

    [`()`]: function(...) {
    ...
    },
    foo: x,
    bar: y
};

1 Answers

Can I apply this functionality to any object?“

No. As of ECMAScript 10th Edition (2019) this is not possible.

The ()-operator/expression construct can only be used on function objects.

This is because it uses the [[Call]] internal method. Section 7.3.12 Call indicates this is only defined for function objects and the specification makes no provision to add the [[Call]] internal method to other objects.

7.3.12 Call ( F, V [ , argumentsList ] )

The abstract operation Call is used to call the [[Call]] internal method of a function object. [..]

The specification is written in such a way that a future revision might add generalized support.

Anyway, as shown in the question, function objects can be mutated as a proxy: so carry on, flavoring as desired.

like image 188
user2864740 Avatar answered Jul 27 '26 05:07

user2864740



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!