Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : missing new prefix when invoking a constructor

I am trying to create a function in node.js. The following is relevant code, it gives me error when i call function.

function ReplacePlaceholders() {
            return 'success';
          }      



  exports.sendMailMsg = function (templateName, receiverEmail, dataPlaceholders) {

        ReplacePlaceholders();
}
like image 848
Anup Avatar asked Feb 06 '14 06:02

Anup


2 Answers

In node.js, function names are camel cased, and should start with a lowercase character. Starting a function with an uppercase character tells JSHint to consider the function a constructor rather than a method.

This is actually an error being generated by JSHint, but the code will run correctly. The option in JSHint, newcap, which causes this error is actually depreciated, and disabling it is recommended.

The relevant info as to why this option is even in JSHint:

This option requires you to capitalize names of constructor functions. Capitalizing functions that are intended to be used with new operator is just a convention that helps programmers to visually distinguish constructor functions from other types of functions to help spot mistakes when using this.

Not doing so won't break your code in any browsers or environments but it will be a bit harder to figure out—by reading the code—if the function was supposed to be used with or without new. And this is important because when the function that was intended to be used with new is used without it, this will point to the global object instead of a new object.

like image 130
Claies Avatar answered Nov 12 '22 22:11

Claies


The error message you mention is a JSHint error message, not a runtime error. There is a discussion of it here:

jshint expects the new 'prefix' for functions

JSHint expects functions that start with a capital letter to be object definitions. You can ignore the error, disable it in JSHint, or rename your function so that it starts with a lower-case letter.

like image 21
Kevin Borders Avatar answered Nov 12 '22 21:11

Kevin Borders