[英]What is the outcome in javascript with multiple librarys that use $
Let's pretend this is in the <head>
of your html page. 让我们假装这是在你的html页面的
<head>
中。
OOPS this was a bit that was missing before... : OOPS之前有点遗漏...... :
<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. 3个脚本的顺序可能会有所不同。 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');
}
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 这就是为什么在(例如)jQuery中有
noConflict()
允许你使用不同的变量而不是$
for jQuery
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.
这就是为什么在定义函数之前检查函数是否已存在的一般做法。 eg
例如
if (typeof $ !== 'function') {
function $(){ /* your code */}
}
or to fail in some sensible way. 或以某种明智的方式失败。
最后一个具有相同名称的函数获胜。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.