How are Function objects different from Normal objects?

試著忘記壹切 提交于 2019-12-05 14:57:31

Yes, functions are special.

Proof

const f = Object.create(Function.prototype);
f(); // TypeError: f is not a function

Exposition

They are "callable objects" that can only be created via prescribed syntax (function expressions, statements, declarations, fat-arrows, object literal method definition shorthand, Function constructor, class methods).

That means they have a special [[Call]] method (not visible to you) that is called when you invoke them with the () syntax.

[[Call]] coordinates:

  • the creation of the execution context (call-stack frame)
  • addition of the new execution context to the top of the stack
  • execution of the function logic
  • removal of the execution context from the stack
  • cueing up the next context to run (the one immediately lower on the stack)
  • supplying any return value to the next execution context

Creation of the execution context in turn completes configuration of the LexicalEnvironment (used for scoping), configuration of the receiver (this) for the function and other meta-logic.

Functions also differ from most normal objects in that they have Function.prototype on their [[Prototype]] chain (although you can create your own 'useless' object by inheriting from Function.prototype - see above).

For a full list of differences, please see MDN, the spec etc.

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