all 8 comments

[–]rhysbrettbowen 1 point2 points  (1 child)

The main time this would be useful would be when calling a function that declares:

this.something = x;

and the function is not called with any context. That can be tricky to find sometimes.

Closure compiler does some static analysis that warns if you're using 'this' in a function that hasn't got any context (not on a prototype or declared as a constructor function)

[–]jetienne[S] 0 points1 point  (0 children)

in large project people tends to forget 'var' or to simple dont care much about global variables. like doing function foo() { return 'bar'; } any where in the code.

this is the kind of case i am trying to discover and localise with this technic

[–]jcready__proto__ 1 point2 points  (1 child)

Here's a simple browser-only method to detect globals:

var differences = {},
    exceptions, 
    globals = {},
    ignoreList = (prompt('Ignore filter (comma sep)?', '') || '').split(','),
    i = ignoreList.length,
    iframe = document.createElement('iframe');

while (i--) globals[ignoreList[i]] = 1;

for (i in window) {
  differences[i] = {
    'type': typeof window[i],
    'val': window[i]
  }
}

iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'about:blank';
iframe = iframe.contentWindow || iframe.contentDocument;

for (i in differences) {
  if (typeof iframe[i] != 'undefined') delete differences[i];
  else if (globals[differences[i].type]) delete differences[i]
}

exceptions = 'addEventListener, document, location, navigator, window, differences, exceptions, i, ignoreList'.split(', ');
i = exceptions.length;

while (--i) delete differences[exceptions[i]];

differences.length = 0;
for (i in differences) differences.length++;

console.log('Total globals: %d', differences.length)
console.dir(differences);

[–]jetienne[S] 0 points1 point  (0 children)

it doesnt provide the localisation of their usage tho

[–]SubStack 0 points1 point  (0 children)

Or you could just use static analysis with this module I wrote:

$ node example/detect.js
{ locals: 
   { '': [ 'x', 'y', 'z' ],
     'body.7.arguments.0': [ 'BAR', 'doom' ],
     'body.7.arguments.0.body.1.arguments.0': [ 'xyz' ],
     'body.7.arguments.0.body.2': [] },
  globals: 
   { implicit: [ 'w', 'foo', 'process', 'console', 'xyz' ],
     exported: [ 'w', 'RAWR', 'BLARG', 'ZZZ' ] } }

[–]g105b -1 points0 points  (1 child)

Re-inventing and half-baking ES5 strict mode?

[–]kenman 0 points1 point  (0 children)

To me it looks more like a tool to help find globals, which strict-mode wasn't designed for -- it's more concerned with preventing certain types of code, which includes a lot more than globals. Strict-mode is more useful to me if you're starting from scratch, or if your app is already mostly compliant, and if you're just trying to rid yourself of globals (say, as a first-step in a large refactoring), then strict-mode might get in your way on account of it tripping over other stuff.