简体   繁体   English

jQuery变量阴影

[英]jQuery variable shadowing

There is strange pattern in jQuery: jQuery中有一个奇怪的模式:

var jQuery = (function() {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
 ...
return jQuery;

})();

What is the practical reason for this? 实际原因是什么? Why not just expose the inner jQuery function? 为什么不公开内部jQuery函数呢? Is it only for name clashes in the inner jQuery and outer jQuery since both are in closures. 它仅用于内部jQuery和外部jQuery中的名称冲突,因为两者都在闭包中。

jQuery.noConflict(true) removes the global name for jQuery. jQuery.noConflict(true)删除jQuery的全局名称。 However, it would be impossible to program the rest of the jQuery library without using some name for the object, so a local, non-exposed name needs to be used. 但是,如果不为对象使用某些名称,就不可能对jQuery库的其余部分进行编程,因此需要使用本地的,未公开的名称。 For convenience, they redefine jQuery as a variable in the scope of the anonymous function. 为了方便起见,它们将jQuery重新定义为匿名函数范围内的变量。

The pattern itself is called module pattern. 模式本身称为模块模式。 It´s not specific for jQuery and it´s not strange but very helpful. 它不是特定于jQuery的,并不奇怪但很有帮助。 It allows for hiding of the objects state and implementation. 它允许隐藏对象的状态和实现。 It also allows for priveleged methods (public methods with access to private data) and other good design principles. 它还允许使用特权方法(可以访问私有数据的公共方法)和其他良好的设计原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM