我一直在为 jQuery“jQueryLog”开发一个插件,以允许调试链选择器和返回值。如果你想检查一下,你可以这样做here http://www.jquerylog.com
这已经是第二个版本了。第一个版本实际上是经过编辑的 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...
我在这里看到的唯一原因是缩小器具有更少的无法被删除的文字。但还有其他原因吗?
这只是将所有变量保留在函数作用域中同时确保它们在定义之前不被使用的更短方法。
In JavaScript 模式 http://shop.oreilly.com/product/9780596806767.do(2010 年 9 月,奥莱利),斯托扬·斯特凡诺夫称之为single var
pattern:
JavaScript 使您可以在一个文件中的任意位置拥有多个 var 语句
函数,并且它们的行为就好像变量是在
函数的顶部。这种行为称为提升。 ... 你用
一个 var 语句并声明多个以逗号分隔的变量。
使用初始值来初始化变量也是一个好习惯
您声明时的价值。这可以防止逻辑错误(所有
未初始化和声明的变量使用值进行初始化undefined
)并提高代码的可读性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)