简体   繁体   English

function 声明的构造函数

[英]Constructor of a function declaration

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?那么 function 声明的构造函数是什么?

The .constructor property is an object is what you can call new on to create another such object. .constructor属性是一个 object,您可以调用new来创建另一个这样的 object。

That is, someF.constructor points to F, and you can use new F() to create someOtherF .someF.constructor指向 F,您可以使用new F()创建someOtherF

So, if F itself is what you want to make a similar type of object - what can you call to construct a function?所以,如果 F 本身就是你想要的类似类型的 object - 你可以调用什么来构造一个 function? 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.换句话说 - 您可以使用new Function创建类似于 F 的东西 - function 可以在调用new时创建实例。

(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 ) (也就是说,这非常不寻常 - 99% 的时间,函数不应该是动态的 - 没有充分的理由使用new Function

The constructor of a function is Function . function 的构造函数是Function

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM