我们都知道,javascript是一种动态语言,其特性在给我们编程带来方便的同时,也带来了不小的麻烦——语法错误,甚至是看起来正常的语法,经常会造成程序不可预知的行为,这给javascript的代码调试带来很大的困扰。但是,我们有另外一种武器可以从一开始就消除这些问题,那就是良好的javascript代码规范。最近在翻看jquery代码,发现里面有很多可取之处。
1. javascript闭包。这是老生长谈了,相信大家都会写。
(function(window,undefined){
})(window)
2. 用OO方式组织程序代码。
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
3. internal 变量永远在闭包的最开始声明,如果可能的话,尽可能地初始化,避免undefined错误。
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
4. 除非一边为"null",否则使用“===”进行布尔判断,而不是“==”。
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
5. 不使用嵌套“if-else”,因为这会影响程序的可读性,而是使用以下这些形式代替:
多if分枝
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
简单类型使用:?表达式
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
利用“||"表达式的截断特性
end: function() {
return this.prevObject || this.constructor(null);
},
6. 在布尔判断时,用”!!"做强制布尔转换。
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
7.使用”||“表达式时,简单在前,复杂在后。
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
8. if判断中使用变量本身而不是"elem!==null"形式。
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
暂时就收集了这么多,相信通过这些优秀的库,我们可以学习更多的javascript代码规范,而使用代码规范来约束编程陷阱提高代码健壮性也是一种优秀的思路。