我一直在为jQuery“jQueryLog”开发一个插件,以允许调试链选择器和返回值。如果你想查看它,你可以here
这已是第二个版本。第一个版本实际上是一个编辑过的jQuery,在做这个时我不得不阅读jQuery来了解内部的工作原理。问题来自那里:
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
(...)
使用声明链+“逗号”是否有任何重要原因,而不仅仅是使用:
function jQuery ( selector, context ) { ... }
var _jQuery = window.jQuery;
var _$ = window.$;
etc...
我在这里看到的唯一原因是缩小器具有较少的文字,无法减少。但还有其他原因吗?
答案 0 :(得分:5)
这只是将所有变量保留在函数范围内的一种较短的方法,同时确保它们在定义之前不会被使用。
在 JavaScript Patterns(2010年9月,O'Reilly)中,Stoyan Stefanov将其称为单var
模式:
JavaScript使您可以在a中的任何位置拥有多个var语句 函数,它们都表现为好像变量是在声明的 功能的顶部。此行为称为提升。 ... 你用 一个var语句并声明由逗号分隔的多个变量。 使用初始值初始化变量也是一种很好的做法 您声明它时的值。这可以防止逻辑错误(全部 未初始化和声明的变量用值初始化
undefined
)并且还提高了代码可读性。