1

I've been rewriting various bits of code I've 'inherited' and come across something I don't understand. Both jslint and jshint think the below function is a constructor, and I have no idea why.

function GEReqsDone(failed) {
    if (!failed) {
        alert('Thank you for your submission! The page will now be reloaded.');
        document.location.replace(mwConfig.wgScript + '?title=' + encodeURIComponent(mwConfig.wgPageName) + '&action=purge');
    } else {
        alert('An error occurred while submitting the edit.');
        button.disabled = false;
        button.innerHTML = 'Update price';
    }
}

This is a callback from query using $.ajax() that queries the mediawiki API to automatically edit to update a price on a page. If the edit succeeds failed is not defined and the page reloads. If it fails, failed is set to true and it resets the button used to trigger the update.

button is simply a button element, the wg* variables are part of the mediaWiki object here used to access the pagename and url prefix (usually /index.php).

Does anyone know why jshint and jslint seem to think this function should be new GEReqsDone() rather than GEReqsDone()?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Onei
  • 177
  • 1
  • 2
  • 11
  • 4
    Constructors are the only functions in JavaScript that should start with a capital letter. JSLint/JSHint will see that it starts with an uppercase G and assume it is a constructor. – RobH Aug 02 '13 at 11:11
  • It's really that simple? Thanks very much. – Onei Aug 02 '13 at 11:12
  • 1
    possible duplicate of [JSLint says new keyword is missing](http://stackoverflow.com/questions/9650392/jslint-says-new-keyword-is-missing) – apsillers Aug 02 '13 at 11:13

1 Answers1

1

Constructors are the only functions in JavaScript that should start with a capital letter. JSLint/JSHint will see that it starts with an uppercase G and assume it is a constructor.

This is the only convention we have to make sure people know that the function should be used as a constructor. Some people write defensively to avoid people missing the new keyword:

var SomeConstructor = function () {
    if (!(this instanceof SomeConstructor)) 
        return new SomeConstructor();
}
RobH
  • 3,604
  • 1
  • 23
  • 46