How does ReSharper recognize a JavaScript constructor function?

Hi,

Just started with R# and I'm getting warnings about naming inconsistencies in my constructor functions in some javscript code.

Example code:

    function MyConstructor(a) {
        this.a = a;
        return this;
    }


This triggers a warning because of the "Inconsistent Naming" inspection. Looking at it, the naming rule it uses is 'Local Function', instead of 'Constructor'.

So, my question is: how do I get R# to recognize this as a constructor? Is there some annotation I can use? I know I can supress the warning locally,
but since there is a javascript naming rule called 'Constructor', it should be possible to get r# to use it?

Note that the 'return this;' statement can be removed with the same result.

Using ReSharper 7.1.3 Full Edition.

be well
-h-
7 comments
Comment actions Permalink

I have the same issue. Any comments from JetBrains?


0
Comment actions Permalink

It looks like a constructor is used when a function is used with the "new" keyword:

MyObject = function() { this.whatever = "hello"; };

obj1 = new MyObject();


MyObject should be classed as a constructor, and if it doesn't match the naming standard, it will display the warning squiggly by the "new" keyword.

0
Comment actions Permalink

Here I use the new keyword...
JavaScript.JPG

0
Comment actions Permalink

Try adding parameters to the function called after new:

js_constructor.png

0
Comment actions Permalink

I think I've found a pattern: R# will apparently think of all functions as local functions if the definition is contained within another function.

So, if you use a self-executing anonymous function to encapsulate everything (as is standard practice in JS development), it won't recognize it as a constructor.

So this will be flagged:

// top level
(function() {
  function ViewModel() {
    ....
  }
  var vm = new ViewModel();
})();

while this won't:

// top level
function ViewModel() {
  ....
} 

var vm = new ViewModel();

be well
-h-

0
Comment actions Permalink

Reproduced. I've created an issue, if you want to vote on it: http://youtrack.jetbrains.com/issue/RSRP-375244

0
Comment actions Permalink

Thank you guys. Henrik seems to be right: my functions are indeed nested functions...

0

Please sign in to leave a comment.