|
|
|
|
|
by barrkel
4054 days ago
|
|
"technically, functions are just objects that can be called" How can you create an object which can be called like a function, but will respond to 'typeof' with 'object' rather than 'function'? What happens when you try to call an object - what's the error? Try it, in a few of your favourite javascript interpreters: ({})()
It seems clear to me that functions are more than "just" objects in JS. You can't start out with a random {} and turn it into a function. JS functions are a subtype of JS objects, but they are a distinct type. 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. |
|
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.