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

我怕爱的太早我们不能终老 提交于 2019-11-29 11:15:27

问题


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?


回答1:


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]'


来源:https://stackoverflow.com/questions/897103/what-is-the-difference-between-a-function-object-and-a-callable-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!