Raine Revere
Raine Revere

Reputation: 33685

What does `var MyConstructor = function MyConstructor()` do?

What's the difference between:

var NodestrapGenerator = module.exports = function NodestrapGenerator() {
  yeoman.generators.Base.apply(this, arguments);
  // more code here
};

and:

var NodestrapGenerator = module.exports = function() {
  yeoman.generators.Base.apply(this, arguments);
  // more code here
};

I'm trying to write my yeoman-generator's index.js in coffeescript, but apparently the second snippet isn't the same because it's not working! Thanks!

Upvotes: 2

Views: 89

Answers (1)

Amy
Amy

Reputation: 7466

var NodestrapGenerator = module.exports = function NodestrapGenerator() { ... };

This is a named function called "NodestrapGenerator", assigned to variable NodestrapGenerator.

var NodestrapGenerator = module.exports = function() { ... };

This is an unnamed function aka. anonymous function, which gets assigned to variable NodestrapGenerator.

In the end, they're both referencing the same function, so no difference which way you write it.

See this for more explanation: var functionName = function() {} vs function functionName() {}

As to why it's not working, its probably because the code is looking for the named function NodestrapGenerator to verify that it's the function it should be using, not some random anonymous function.

FYI, function has a property name which will get set to "NodestrapGenerator" in named function (first example), but will be empty string "" in anonymous function (second example). (See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/name)

Upvotes: 4

Related Questions