Javascript validation/inspection: Detect the use of undeclared methods or properties of an object

StackOverflow https://stackoverflow.com/questions/22934944

  •  29-06-2023
  •  | 
  •  

Domanda

Please consider the following code.

The following is according to JSLint or JSHint perfectly valid Javascript code:

function fun() {
    "use strict";
    var myvar = "";
    myvar.foo();
}

The following not:

function fun() {
    "use strict";
    var myvar = "";
    foo();
}

Why is JSLint (or JSHint) not detecting that myvar.foo() wasn't declared before, whereas it detects that foo() wasn't declared? Is there an option which I'm missing?

I would like those types of errors to be detected upon validation. Is there another javascript tool which can detect the use of undeclared properties or methods inside an object as explained in the examples above?

È stato utile?

Soluzione

All linters simply ready your code, they don't run it. In your case, it's impossible to tell whether myvar.foo was defined or not. As for foo() if you defined it within the same file, JSHint will detect that. Otherwise, it won't.

Altri suggerimenti

Linters just parses/scans your code for "problems". If you really want to test your code you need to use unit testing.

like Qunit: https://qunitjs.com/

JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
http://www.jslint.com/lint.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top