Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a function object and a callable object?

I recently saw the presentation about the changes in ECMAScript 5. And there was a slide with this statement:

Function vs Callable

typeof f === 'function'                       // → f is Callable
({}).toString.call(f) === '[object Function]' // → f is a Function

Can anyone explain to me what the difference between Function and Callable is?

like image 267
Gumbo Avatar asked May 22 '09 09:05

Gumbo


1 Answers

Generally speaking, an object can be callable without being a function. In a language where everything is an object (including functions), callable objects don't have to descend from a Function class.

In JS, it looks like a Callable is anything that has the internal [[Call]] method (identified by a typeof of 'function', as opposed to 'object'). A Function (as used in the slide) is a descendant of the Function object. I could be wrong, but within a script you can only create Functions while the ECMAScript implementation can define Callables that aren't Functions.

If you try the code fragment from the slide with both anonymous functions/function expressions and with declared functions, the results are the same.

typeof function() {}; // == 'function'
({}).toString.call(function() {}) // == '[object Function]'
function foo() {}
typeof foo; // == 'function'
({}).toString.call(foo) // == '[object Function]'
like image 109
outis Avatar answered Nov 13 '22 05:11

outis