简体   繁体   English

对JavaScript中的构造函数感到困惑

[英]Confused about constructors in javascript

Please excuse me if I am missing anything important or even silly. 如果我错过任何重要甚至愚蠢的事情,请原谅。 I'm trying to print the constructor's name from objects. 我正在尝试从对象中打印构造函数的名称。 I followed two approaches. 我遵循两种方法。

First approach's code is below, 第一种方法的代码如下,

var CF = function () {
   p1 = "";
   p2 = "";
}
var cf1 = new CF();
cf1.constructor.name

Output : 输出:

""

second code, 第二个代码

function CF() {
   p1 = "";
   p2 = "";
}
var cf1 = new CF();
console.log(cf1.constructor.name);

Output : 输出:

CF 

I guess you have undertood what I wanted to say. 我想你已经理解了我想说的话。 The first CF 's objects constructor name is "" where as second ones output is CF . 第一个CF的对象构造函数名称为"" ,第二个输出为CF

I tried to know the differnce like below 我试图知道下面的区别

var CF = function() { }
typeof CF;
function CF() { };
typeof CF

But no luck they both output 但是他们俩都没有运气

"function"

Why is that behavior with first approach? 为什么采用第一种方法会有这种行为? What is the difference? 有什么区别?

(I'm using chrome console) (我正在使用Chrome控制台)

The first constructor function is an anonymous function meaning it has no name. 第一个构造函数是一个匿名函数,意味着它没有名称。 The second constructor function has a name which allows its constructor to be printed. 第二个构造函数的名称允许打印其构造函数。

In the first approach you just create an object named CF that contains an unnamed function that is a constructor for a class which is unknown until that point. 在第一种方法中,您仅创建一个名为CF的对象,其中包含一个未命名的函数,该函数是该类的构造函数,该类在该点之前是未知的。

In the second code you write the constructor for the class in a function named CF and then use that constructor to create an instance of your class in the object named cf1. 在第二个代码中,您在名为CF的函数中编写类的构造函数,然后使用该构造函数在名为cf1的对象中创建类的实例。

I hope you understand what I'm trying to say, basically your first constructor has no name. 希望您理解我要说的内容,基本上您的第一个构造函数没有名称。

function CF() { }; is shorthand for var CF = function() { } , so typically they are the same. var CF = function() { }简写,因此通常它们是相同的。

That being said, function CF() { }; 就是说, function CF() { }; gives you some benefit in debugging in node, since it allows node to give more precise feedback on what/where went wrong. 在节点上进行调试会给您带来一些好处,因为它使节点可以对发生问题的地方/位置提供更精确的反馈。

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

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