Function objects

·

2 min read

This is just a quick note to link somewhere else, so don't mind me! Its purpose isn't precision nor completion.

Functions are objects. They have an internal [[Call]] slot, which is what really distinguishes it from regular objects. But they are objects, nevertheless. A bit special, but objects.

Sometimes we refer to them as function objects or callable objects.

As these are objects, functions are attached to a prototype chain pointing towards Function.prototype (which is a function object itself!).

It has some properties:

  • name: the name of the function if given; if not given and it's a function expression, then the name of the variable holding it, if applicable.
  • length: the number of arguments expected on its signature.
  • caller and arguments.

They also have an extra internal slot: [[Construct]]. This allows some functions (called constructor functions) to create objects.

This is what declaring a function means: creating a function object which is primarly composed by the stuff we've discussed so far.

Functions as object, visually

Given

const add = function(a, b) {
    return a + b
}

, you can imagine add as

const add = {
    name: 'add',
    length: 2,
    caller: null,
    arguments: null,
    __proto__: Function.prototype,
    [[Call]]: @@{return a + b} /** no clue how to represent this */
    [[Construct]]: @@{I create objects} /** no clue how to represent this neither */
}