我继承了一些用以下方式包装的 javascript 代码:
(function ($) {
//some javascript using jQuery here...
} (jQuery));
它有什么作用?
最佳答案
它立即调用匿名函数,将全局 jQuery
作为参数传递给函数调用,然后由 $
参数引用。
这确保 $
是该函数的局部变量,因此如果其他库正在使用全局 $
标识符,它不会发生冲突。
可以这样想:
// create a function that receives jQuery as an argument
function keepItLocal( $ ) {
// execute your jQuery code in here
// where $ is now a reference to jQuery
};
// invoke the function, passing in the global jQuery
keepItLocal( jQuery );
因为在 JavaScript 中限定变量范围的唯一方式是在函数中,这是防止全局命名空间污染的常见模式。
如果我们这样做:
$ = jQuery;
$('.someClass').someMethod();
...如果 $
之前已定义,我们可能会覆盖它,或者其他一些代码可能会出现并覆盖它。
关于javascript - jQuery/javascript 包装代码查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5145278/