How are Function objects different from regular objects?

How are functions stored in a variable?

According to MDN

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What sets them apart from other objects is that functions can be called. In short, these are Function objects.

Suppose this scenario

var fn = function () {};
fn.attr = 3;

console.log(fn); //prints function() {}

console.log(Object.keys(fn)); //prints ["attr"]

If a function is an object, it does not have keys and values, where is the function stored in the property, and the interpreters do not display this property? Something like overloading a C ++ style statement or representing an array / object in Javascript itself. I want to say that functions (or arrays) are just objects processed in a different way? This may mean that anonymous functions are stored in an object with a hidden property.


So what is the main function (or array) operation? Are they specially treated? Or is it just syntactic sugar for some hidden property that gets called when used ()?

+4
source share
1 answer

Yes, the features are special.

Proof

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

Exposition

" ", ( , , , , , Function, class).

, [[Call]] ( ), ().

[[Call]]:

  • ( -)
  • (, )

, , LexicalEnvironment ( ), (this) -.

, Function.prototype [[Prototype]] ( "" , Function.prototype - . ).

MDN, ..

+5

Source: https://habr.com/ru/post/1675894/


All Articles