Effective JavaScript :第六章

1.将undefined看成没有值

产生undefined的情况:

①未赋值的变量的初始值为undefined。

var x ;
X ;      //undefined

②访问对象中不存在的属性也会产生undefined。

var obj = {} ;
obj.x ;       //undefined

③函数体结尾使用未带参数的return语句,或未使用return语句都会产生undefined。

function f(){
    return ;
}
function g(){};
f();    //undefined
g();   //undefined

④未给函数参数提供实参则该函数参数值为undefined。

function f(x){
    return x ;
}
f();    //undefined 

2.接收关键字参数的选项对象

一个函数起初很简单,然而一段时间后,随着库功能的扩展,该函数的签名会获得越来越多的参数。尝试理解下面的函数调用:

Var alert = new alert(100,75,300,200,
                      ”error”,message,
                      ”blue”,”white”)

幸运的是,JavaScript提供了一个简单的、轻量的惯用法:选项对象。选项对象在应对较大规模的函数签名时运作良好。

var alert = new alert({
    x : 100 , y : 75 ,
    width : 300 , height : 200 ,
    title : “error”, messagr : message ,
    titleColor : “blue”, bgColor : “white”
})

选项对象的好处是易于阅读,所有参数都是可选的,调用者可以提供任一可选参数的子集。

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 ;
}

3.区分数组对象和类数组对象

①API绝不应该重载与其他类型有重叠的类型

②当重载一个结构类型与其他类型时,先测试其他类型。

③当重载其他对象类型时,接收真数组而不是类数组对象。

4.支持方法链

无状态的API的部分能力是将复杂操作分解为更小的操作的灵活性。一个很好的例子是字符串的replace方法。

在无状态方法中返回新对象来支持方法链:

var users = records.map(function(record){
    return record.username ;
})
.filter(function(username){
    return !!username ;
})
.map(function(username){
    return username.toLowerCase() ;
}) ;

有状态的API的方法链有时被称为流畅式。如果更新方法没返回this,那么API的使用者不得不每次重复该对象的名称。例如:

$(“#notification”)
.html(“Server not responding.”)
.removeClass(“info”)
.addClass(“error”) ;
原文地址:https://www.cnblogs.com/koto/p/5522392.html