views:

583

answers:

1

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?

+6  A: 

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]'
outis
And to enlighten outis' response, here is a discussion on how it came to be: http://bugs.ecmascript.org/ticket/153
Fran Corpier
Further information:(function(){}).constructor; // → Function prototype({}).constructor; // → Object prototype
ken