Doug Chamberlain
Doug Chamberlain

Reputation: 11341

What is the outcome in javascript with multiple librarys that use $

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');
}

Upvotes: 10

Views: 419

Answers (3)

lonesomeday
lonesomeday

Reputation: 237905

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.

Upvotes: 16

Ry-
Ry-

Reputation: 224942

The last function with the same name wins.

Upvotes: 5

Naftali
Naftali

Reputation: 146310

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

Upvotes: 18

Related Questions