Home > Article > Web Front-end > Decomposition of the implementation principle of noconflict function in jQuery_jquery
In jQuery, noconflict is an important method used to prevent variable conflicts and release control of variables. We know that jQuery provides two global variables to the outside world, $ and jQuery. Although jQuery only generates two global variables, conflicts will only occur in rare cases. However, if the web page contains more class libraries, there will be automatic A conflict occurs when defining $ or the existence of a jQuery global variable.
The noconflict function provided by jQuery solves the variable conflict problem very well. Whether it is $ or jQuery conflict, it can be solved. Next, let’s analyze jQuery’s conflict handling.
First, let’s take a look at the implementation of noconflict in the jQuery source code:
(function(window,undefined){ var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery.extend({ noConflict: function( deep ){ if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; } }) }(window)
Here jQuery.extend is jQuery's method of extending static properties. This can be seen as directly attaching the noConflict method to jQuery. Inside the anonymous function, define internal variables _jQuery and _$ respectively to store window.jQuery and window.$. The purpose of this is to use internal variables to save the state of these two global variables before jQuery is run, so that they can be used later. These two variables are restored in the anti-collision operation. noConflict can handle the conflict between the two variables $ and jQuery. It handles $ by default. If a true parameter is passed in, the jQuery conflict will be handled.
window.$ === jQuery is used to determine whether the global variable is equal to jQuery. If it is equal, the global variable $ is restored to the variable before jQuery was run (stored in the internal variable _$); deep && window.jQuery === jQuery When deep conflict handling is enabled and the global variable jQuery is equal to the internal jQuery, the global jQuery is restored to its previous state. The significance of judging window.$ === jQuery and window.jQuery=jQuery is to protect the defined variables from being overwritten, such as the following code:
//引入jQuery库 var $="String"; var jq=jQuery.noconflict(); var jQuery="This is a line"; var j=jq.noconflict(true); console.log($);//这里如果没有window.$===jQuery这句判断,那么$将会等于undefined而不是"String"。 console.log(jQuery); //同上,如果没有判断window.jQuery===jQuery,重新定义的jQuery就会被undefined覆盖。
The entire operation process is shown in the figure below:
noConflict returns the jQuery constructor inside the jQuery library, use it like $!