源碼如下:
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
第一種情況:
<script src="./jquery3.2.1.js"></script>
<script>
var $ = 111;
$(function(){
console.log('11111111')
})
</script>
當(dāng)給$賦值111時(shí),會(huì)引起變量名沖突,$名字被別人占用,代碼無(wú)法執(zhí)行。
<script>
var jq = $.noConflict()
var $ = 111;
jq(function(){
console..log('11111111')
})
</script>
這時(shí)noConflict()方法派上了用場(chǎng),給jQuery取了別名jq,$讓給別人,解決變量名沖突。
第二種情況:
<script>
var $ = 11111;
</script>
<script src="./jquery3.2.1.js"></script>
<script>
var jq = $.noConflict()
jq(function(){
console.log($) // 1111
})
</script>
看源碼知道在加載jquery時(shí),已經(jīng)把沖突的變量名的值存到_jQuery或者_(dá)$; 加載jquery后 ,$又變成jQuery ,用noConflict方法解決變量名沖突后,jquery放棄使用$或者jQuery的名字,把_jQuery 或者_(dá)$的值重新賦給$或者jQuery,jquery使用jq別名。