Home > database >  Constructor of a function declaration
Constructor of a function declaration

Time:04-12

Why does the following hold:

let F = function () {};
let f = new F();
console.log(f.__proto__.constructor === F, f.constructor === F);
// true

But the following does not:

let F = function () {};
console.log(F.prototype.constructor === F, F.constructor === F);
// true false

What then would be the constructor of a function declaration?

CodePudding user response:

The .constructor property is an object is what you can call new on to create another such object.

That is, someF.constructor points to F, and you can use new F() to create someOtherF.

So, if F itself is what you want to make a similar type of object - what can you call to construct a function? Function.

let F = function () {};
console.log(F.constructor === Function);

In other words - you could use new Function to create something similar to F - a function that can create instances when new is called on it.

(That said, this would be extremely unusual - 99% of the time, functions should not be dynamic - there's no good reason to use new Function)

CodePudding user response:

The constructor of a function is Function.

let F = function () {};
console.log(F.__proto__.constructor === Function, F.constructor === Function);
// true false

  • Related