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({
    		 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({1200,height:1000},{title:'child',modal:'true'});
  • 尽可能使用无状态的API;

并发:

  • 不要阻塞I/O事件队列;
  • 使用嵌套或命名的回调函数顺序地执行多个异步操作:
    db.lookupAsync('url', function(url) {
       downloadAsync(url, function(text) {
         console.log('contents of ' + url + ': ' + text);
       })
    })
    --------------优化---------------
    db.lookupAsync('url', downloadURL);
    
    function downloadURL(url) {
       downloadAsync(url, function(text) {
          showContents(url, text);
       })
    }
    function showContent(url, text) {
        console.log('contents of ' + url + ': ' + text);
    }
    ---------------优化-------------
    db.lookupAsync('url', downloadURL);
    function downloadURL(url) {
       downloadAsync(url, showContents.bind(null, url));
    }
    function showContents(url, text) {
       console.log('contens of ' + url + ': ' + text);
    } 

    在过多嵌套的回调函数和尴尬的命名的非嵌套回调函数之间取得平衡;

  • 当心丢失错误:
    • 表现
      • 异步的API不会抛出异常,因为当一个异步的错误发生时,没有一个明显的执行上下文抛出异常;
      • 异步API倾向于将错误表示为回调函数的特定参数,或使用一个附加的错误处理回调函数;
原文地址:https://www.cnblogs.com/jinkspeng/p/4151009.html