-1

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.

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)

1
  • 2
    The function expression sets an unamed function to a variable, the function has no name, Commented Mar 4, 2014 at 10:36

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Simple and precise :)
1

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.

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.

I hope you understand what I'm trying to say, basically your first constructor has no name.

Comments

0

function CF() { }; is shorthand for var CF = function() { }, so typically they are the same.

That being said, function CF() { }; gives you some benefit in debugging in node, since it allows node to give more precise feedback on what/where went wrong.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.