Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> How can you create an object which can be called like a function, but will respond to 'typeof' with 'object' rather than 'function'?

You can't, by definition. Here is the relevant section of the ECMAScript 5 spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3

Basically, an object which implements call will always cause `typeof` to return "function". But the broader point is that `typeof` will lie to you and you shouldn't trust it for, you know, determining the types of values. (For example, the type of null is null, but `typeof null` returns "object".)

As I noted above, this behavior of `typeof` is part of what causes the confusion around types in JS devs.

> You can't substitute an object where a function is expected - you get a type error - but you can substitute a function where an object is expected.

This is true, but not inconsistent with the notion that functions are objects which can be called. I encourage you to read the spec I linked above, or a draft of ES6.



There's types as defined in a spec, and types according to type theory.

In short, I think the spec is incorrect in its use of the concept of types; or incomplete.

You'll note that the spec uses the concept of "internal properties" to distinguish between the different things one can do with values. From a type theory perspective, these internal properties and the implied permitted operations come close to type definitions. It's a matter of perspective, then, when one is using the word 'type' as defined by a particular language's spec, or 'type' as in programming language pragmatics / type theory POV. For the generalist programmer who knows more than one language, a broader concept of types is usually more useful.

Further, the spec uses these internal properties solely to define the semantics of the language, and they are not necessarily visible artifacts of any implementation. Talking about them as if they were concrete confuses the map with the territory.


>Basically, an object which implements call will always cause `typeof` to return "function".

Are there any implementations which actually do this? In Node:

typeof({ call: function () { } }) --> 'object'

({ call: function () { } })() --> TypeError: object is not a function




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: