Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool that detects duplicate javascript function names in a web page?

Tags:

javascript

Background

We have a web application in which several developers have written several .js files that manipulate the DOM and the problem of duplicate function names has crept into our application.

Question

Can anyone recommend a tool that will warn us when we accidentally write a web page with two javascript functions with the same name?

Example

HTML page

<script language="JavaScript" src="test.js" type="text/javascript"></script>
<script>function foo() {alert('bar');}</script>

test.js

function foo() {alert('foo');}

Since foo() is declared twice in the page, apparently only the one that takes precedence is loaded.

The tools I've used seem to ignore this. Firebug only shows the loaded function. Netbeans will show both functions in navigator (without a warning), but only looks at one file at a time (ie, I can't point it at the HTML file and see it and the .js at the same time.) and web developer extensions allows me to look at everything at once, but no errors or warnings. Firefox's error console also throws no warning or error. Neither does IE.

Thanks!

like image 321
steve Avatar asked Nov 17 '08 15:11

steve


2 Answers

Well, using a parser may not always be ideal as it requires an extra step of copying and pasting your code, and everyone else's, into the parser and even then I'm not sure it would catch what you want. The time tested solution to collaborative Javascript development is to namespace your code.

var myNamespace = function (){
   var myPrivateProperty;
   var myPrivateFunction = function(){};
   return{

      myPublicProperty: '',
      myPublicFunction: function(){}


   }

 }();

This is based on Douglas Crockford's module pattern.

Then you can call your public functions this way:

 myNamespace.myPublicFunction();

And your public properties:

 myNamespace.myPublicProperty;

Each developer can develop in their own namespace so as to not step on others' code.

like image 128
picardo Avatar answered Oct 18 '22 00:10

picardo


I have often used JSLINT

In short it is a "compiler" for JavaScript using JavaScript. I have learned a lot by watching Douglas Crockford’s training videos.

It not only checks for duplicate functions, but global variables, and a whole bunch of other things. Like Douglas said in one of his videos it allows you to only use the good bits of JavaScript

like image 37
Rihan Meij Avatar answered Oct 17 '22 23:10

Rihan Meij