首页 > 代码库 > javascript高质量编码04

javascript高质量编码04

库和API的设计:

  • 在参数设计中保持好的习惯:如顺序,width,height;top,right,bottom,left;如命名;
  • 将undefined看作没有值而不要表示非特定的值;
  • 在允许0,空字符串等为有效参数的地方,不要通过真值测试(||)来实现参数默认值;
    使用//var x === undefined ? 0 : x;  
  • 接受多参数对象的时候可以选用选项对象;
  • 在处理多个预设值的时候可以用extend
    function extend(target, source) {	if(source) {		for(var key in source) {			var val = source[key];			if(typeof val !== ‘undefined‘) {				target[key] = val;			}		}	}	return target;}function Alert(parent, opts) {	opts = extend({		width: 320,		height: 240	}, opts);	opts = extend({		x: (parent.width/2) - (opts.width),		y: (parent.height/2) - (opts.height),		title: ‘Alert‘,		icon: ‘info‘,		modal: false	}, opts);	extend(this, opts);}var alert = new Alert({width:1200,height:1000},{title:‘child‘,modal:‘true‘});
  • 尽可能使用无状态的API;

javascript高质量编码04