10

Let's pretend this is in the <head> of your html page.

OOPS this was a bit that was missing before...:

<script type="text/javascript" src="/include/js/billys.js"></script>
<script type="text/javascript" src="/include/js/susies.js"></script>
<script type="text/javascript" src="/include/js/marys.js"></script>

Order of the 3 scripts could vary. What would be the outcome?

Billy defines $ as

function $ () {
 return false;
}

Susie defines $ as

function $ () {
 return document.getElementById('body');
}

Mary defines $ as

function $ () {
 alert('I wrote this');
}
Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91

3 Answers3

18

Whatever is last is the final definition of $

That is why in (for example) jQuery there is noConflict() which lets you use a different variable than $ for jQuery

Naftali
  • 144,921
  • 39
  • 244
  • 303
16

Why not try it?

function $ () {
 return false;
}
function $ () {
 return document.getElementById('body');
}
function $ () {
 alert('I wrote this');
}
$(); // alerts "I wrote this"

The later definition overwrites the existing one. This is why it's generally good practice to check whether a function already exists before defining it. e.g.

if (typeof $ !== 'function') {
    function $(){ /* your code */}
}

or to fail in some sensible way.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
5

The last function with the same name wins.

Ry-
  • 218,210
  • 55
  • 464
  • 476